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
  • 9,642
  • 4
  • 31
  • 49
dangerChihuahua007
  • 19,401
  • 30
  • 112
  • 205

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
  • 57,599
  • 16
  • 82
  • 120
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
  • 934
  • 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. – Dmitry Mar 10 '13 at 05:03