0

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.

Community
  • 1
  • 1
alex
  • 460,746
  • 196
  • 858
  • 974

5 Answers5

3

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
  • 74,301
  • 10
  • 131
  • 146
3

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
  • 890,778
  • 177
  • 1,125
  • 1,260
2

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
  • 5,606
  • 20
  • 24
1

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
  • 703,665
  • 143
  • 1,211
  • 1,438
0

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
  • 37,346
  • 9
  • 89
  • 113