Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the binary representation of a number in C? [duplicate]

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

Still learning C and I was wondering:

Given a number, is it possible to do something like the following?

char a = 5;
printf("binary representation of a = %b",a);
> 101

Or would i have to write my own method to do the transformation to binary?

like image 612
Paul Wicks Avatar asked Mar 31 '09 04:03

Paul Wicks


2 Answers

There is no direct way (i.e. using printf or another standard library function) to print it. You will have to write your own function.

/* This code has an obvious bug and another non-obvious one :) */
void printbits(unsigned char v) {
   for (; v; v >>= 1) putchar('0' + (v & 1));
}

If you're using terminal, you can use control codes to print out bytes in natural order:

void printbits(unsigned char v) {
    printf("%*s", (int)ceil(log2(v)) + 1, ""); 
    for (; v; v >>= 1) printf("\x1b[2D%c",'0' + (v & 1));
}
like image 194
dirkgently Avatar answered Oct 23 '22 09:10

dirkgently


Based on dirkgently's answer, but fixing his two bugs, and always printing a fixed number of digits:

void printbits(unsigned char v) {
  int i; // for C89 compatability
  for(i = 7; i >= 0; i--) putchar('0' + ((v >> i) & 1));
}
like image 37
Chris Lutz Avatar answered Oct 23 '22 10:10

Chris Lutz