How to Print a Binary Number in C++

I needed to print out a binary number in C++ for debugging purposes, so I searched for “c++ print binary number”.


I am frankly amazed that every hit on the first page of results led to variations of the same solution: a for loop that checked each bit by shifting a '1' and then building a string or printing 1's and 0's.

Talk about "reinventing the wheel"...

for (int bit = 0 ; bit <= 32 ; bit++) {
    if (value & (1 << bit)) {
        // do something with "1"
    else {
        // do something with "0"

… or something to that effect.

It’s sad how many times this little bit of logic has been written, and re-written, and re-written, just to get a binary string representation of a number!

Thankfully, we live in an age where we have C Plus Plus and the STL.  Because no one should ever have had to write the above code since probably sometime in the 80’s!

The std::bitset class does this for us:

int value = 12345;
cout << bitset<32>(value).to_string() << endl;

This might only save 20 lines of code or so, but it will save time writing it and maintaining it.  The less code the better!

More by this Author

  • Real Reviews: A Quest for Comfortable Feet

    My wife and I took a trip to Europe as a last hurrah before having kids. It was an amazing experience. But we also did so much walking, it was also amazingly painful! I wish I'd done my searching for insoles before that...

  • Real Reviews: The Best Digital Sports Watch

    I've always been a bit disappointed with digital watches I've owned in the past. But I've never wanted to spend a lot on a watch I was planning to be rough on. So, I always ended up with a cheesy, low-quality digital...

Comments 1 comment

platinumOwl4 profile image

platinumOwl4 7 years ago

I am person attempting to learn how to program. Maybe you could give me some advice. During your brief search you made a startling discovery there are many variation of the same information. This can really confuse a novice. Thanks for the information.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.

    Click to Rate This Article