ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

How to Print a Binary Number in C++

Updated on November 12, 2011

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

*sigh*

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!

Comments

    0 of 8192 characters used
    Post Comment

    • platinumOwl4 profile image

      platinumOwl4 8 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.