C printing bits

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.


You are calculating the result correctly, but you are not printing it right. Also you do not need a second loop:

for(;i<size*8;++i){
    // print last bit and shift left.
    printf("%u ",num&maxPow ? 1 : 0);
    num = num<<1;
}

If you'd like to show off, you could replace the conditional with two exclamation points:

printf("%u ", !!(num&maxPow));

To address point two, I'd consider the following, which is simplified a bit for ease of understanding.

void printBits(unsigned int num)
{
   for(int bit=0;bit<(sizeof(unsigned int) * 8); bit++)
   {
      printf("%i ", num & 0x01);
      num = num >> 1;
   }
}

Tags:

C