Tuesday, February 7, 2012

Print a number in HEX format

In hex notation we have 4 bits representing each unit of the hex number. So "A" in hex is represented as 1010. But in a int there are 32 bits so 32/4 is 8 and we need to loop 8 times to convert to an hex number.


int main() 
{
int num,i=0,index;
char buff[17]="0123456789ABCDEF";
printf("Enter Num: ");
scanf(" %d",&num);

printf("0x");
for(i=7;i >= 0;i--)
{
index = ((num >> i*4)&15);
printf("%c",buff[index]);
}
printf("\n");
}

No comments:

Post a Comment