Thursday, August 24, 2006

Hex Format

PRINT A NO IN HEX FORMAT

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

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

3 comments:

Anonymous said...

Hi ..
Can you lemme know what is the logic behind ur program ? Y did u use 7 ?

Ghotter said...

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.

Aravind said...

Will this logic works for negative integer also?