0

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

Is there any built in function to convert a decimal number to binary number? Is there any format specifier for binary numbers? For hex it is %x and for binary?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

No, C does not have binary conversion functions built in. However, they're not hard to write and are a good exercise to demonstrate your understanding of binary arithmetic.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
-1

some libc have it as extension (you can printf a %b ) but here is a basic macro implementation if you just need the string representation of the binary

#define putbin(d) do{ \ 
  unsigned long long i=1ULL<<63; \ 
  while (!((unsigned long long) d & (i/=2))); /* optional - remove leading zeroes */ \ 
    do { ( (unsigned long long) d & i) ? write(1,"1",1) : write(1,"0",1); } \
    while (i/=2); \ 
write(1,"\n",1); /* optional - add new line */ \ 
} while (0)
technosaurus
  • 7,676
  • 1
  • 30
  • 52