I am trying to create a function to print a number in binary using bitwise and bit shifting but I am having trouble printing it correctly. The following is my code.
void PrintInBinary( unsigned int decNum )
{
int i = 0;
unsigned int highestOne = 1 << (sizeof(unsigned int)*8 - 1);
for( i = 0; i < sizeof(int)*8; i++ ) {
printf( "%u", decNum & (highestOne >> i) );
}
printf("\n");
}
int main()
{
unsigned int a = 128;
PrintInBinary( a );
system("PAUSE");
return 0;
}
The following is the output:
0000000000000000000000001280000000
Basically, its printing the 2^bit rather than just a 1 at each bit position (for example if I wanted to convert 7 to binary it would be 0000000...00421 instead of 0000000...00111). This is probably something trivial I'm missing, but any help guys? I've been at this for the last 20 min at can't figure out something so simple.
Change
decNum & (highestOne >> i)to(decNum & (highestOne >> i)) != 0.Many people also like to write
!!(decNum & (highestOne >> i)). I concede it's cute, but it's less readable and I would suggest that you don't use this.