tags:

views:

93

answers:

5

Possible Duplicate:
Is there a printf converter to print in binary format?

Consider this small C application

int main () {
    int bits = 100 >> 3;    
    printf("bits => %d", bits);     
    return 0;
}

How can I print the bits variable so I can see it as a binary value (with the bits clearly shifted), e.g. 00001100?

I'm also learning, so feel free to correct any terminology.

+2  A: 

You have to extract one bit at a time. Something like the following

int main() {
  int bits = 100 >> 3;
  for (int bit = 7; bit >= 0; --bit)
    printf("%d", (number & (1 << bit)) == 1);
  printf("\n");
  return 0;
}
torak
Wouldn’t this print the bits in reverse order?
Timwi
Would have indeed. Thanks for the catch. Fixed it.
torak
+3  A: 

This should work (not tested):

#define PRINT_BITS 7

void printbits(int input){
    int i, mask;

    for(i=PRINT_BITS; i >= 0; i--){
       mask = 1 << i;
       if(input & mask){
          printf("1");
       }else{
          printf("0");
       }
    }
 }
WoLpH
It indeed does work! :) Thanks
alex
+2  A: 

Experienced programmers will usually print the value out in hex ("%x" in the format string), because there is a simple correspondence between hex digits and each group of four binary bits:

Hex Binary
 0   0000
 1   0001
 2   0010
 3   0011
 4   0100
 5   0101
 6   0110
 7   0111
 8   1000
 9   1001
 A   1010
 B   1011
 C   1100
 D   1101
 E   1110
 F   1111

It would do well to commit this table to memory.

Greg Hewgill
yeah there's very little reason to use straight binary it's too many digits
Matt Joiner
+1  A: 

You'll need to extract the bits one at a time and print them out to the screen. Here's a simple function

void printBits(int value) {
  int bits = sizeof(int)*8;
  int mask = 1 << (bits-1);
  while ( bits > 0 ) {
    putchar((mask & value) ? '1' : '0');
    bits--;
  }
}
JaredPar
A: 

Try this:

int number = 0xEC; 
for (int bit = 128; bit != 0; bit >>= 1) printf("%d", !!(number & bit));

If you want to avoid the heavy runtime of printf function, just use putchar:

putchar(!!(number & bit) + '0');
Michael Buen