I am trying to write a program in C that prints bits of int. for some reason i get wrong values,
void printBits(unsigned int num){
unsigned int size = si
The result you get is because num&maxPow
is either 0 or maxPow
. To print 1 instead of maxPow
, you could use printf("%u ", num&maxPow ? 1 : 0);
. An alternative way to print the bits is
while(maxPow){
printf("%u ", num&maxPow ? 1 : 0);
maxPow >>= 1;
}
i.e. shifting the bitmask right instead of num
left. The loop ends when the set bit of the mask gets shifted out.