3

I am trying to print out an unsigned value in binary in C++. I have found many hacks for this task such as

http://www.java2s.com/Tutorial/Cpp/0040__Data-Types/Printinganunsignedintegerinbits.htm

However, I feel that there should be a much more straightforward way, perhaps with sprintf. After all, there are very straightforward ways to print a value in hex or octal.

jrd1
  • 10,358
  • 4
  • 34
  • 51
dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206

2 Answers2

7

Simple - Use STL bitset:

e.g.

bitset<10> n (120ul); // 10 bits in this case
cout << n.to_string() << endl;
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
4

printf familiy does not support base-2 printing. You need to use a custom or non-standard function, such as itoa (just set the base/radix to 2).

John Smith
  • 980
  • 1
  • 8
  • 15
  • Indeed, there is no way to write a base two printf/cout without resorting to bit masking and shifting. Although you can resort to other magic, or look around for libraries that do support it. – Dmytro Mar 10 '13 at 05:03