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.

2 Answers 2

7

Simple - Use STL bitset:

e.g.

bitset<10> n (120ul); // 10 bits in this case cout << n.to_string() << endl; 
Sign up to request clarification or add additional context in comments.

Comments

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).

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.