Flag This Hub

How to Print a Binary Number in C++

By


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!

  • Hungarian Notation - You Should Reconsider It

    I used to think that Hungarian Notation was silly. I had a hard time seeing the point of it, and it just seemed like visual clutter when reading code. Eventually, I ended up working on a team that... - 6 months ago

  • Add to the Java Classpath at Runtime

    When writing an application, in any programming language, one often needs to load data from an external resource. This is typically a file on the filesystem, in which case one writes code to open the... - 6 months ago

  • Java: getResource() vs. getResource() ...er, huh?

    The 'getResource' method in Java allows applications to get files and other resources generically, without hard-coded knowledge of the type of resource, as long as it's in your class... - 6 months ago

  • Droj's Javascript Evaluator Tool

    When learning Javascript, one of the most valuable tools you can have is a way to run snippets of code on the fly, without editing a file, then saving it, then reloading the page in your browser. You... - 6 months ago

  • How to Improve Performance of Shell Scripts

    Shell scripts in Linux/Unix have the potential to do a lot of work. A lot of times they will start out as just a couple of lines written as a convenience to avoid typing in a few commands repeatedly.... - 6 months ago

Comments

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

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working