Home > C++ > Printing numbers in binary format in C++

Printing numbers in binary format in C++


The problem

You want to display or output a number in binary format. Iostream only has output manipulators for decimal, hexadecimal and octal.

The bad solution

People usually write a loop to do this that iterates over each bit in the integer:

int v = 0x12345678;
for (int i = 31; i >= 0; i--)
    std::cout << ((v >> i) & 1);

There are many ways to do this; the loop above shifts the bit to print into the least significant bit (bit 0) of a temporary and ANDs it with 1 to remove all the other (higher order) bits and leave a 0 or 1. It starts with the most significant bit (31) and iterates down to the least significant bit (0), ensuring that the bits are printed in the correct order.

The good solution

While a looping solution still has applicability in some other languages, there is a much more elegant way to do it in C++ that is often overlooked:

int v = 0x12345678;
std::cout << std::bitset<32>(v);

The C++ standard library includes a container type bitset whose first non-type template parameter specifies the number of bits to store. It includes an overload for operator<< and a conversion constructor for ints, making printing binary numbers a piece of cake! This is a much preferred solution to the messy for loop construct above.

To use bitset, remember to add:

#include <bitset>

at the top of your code.

Good luck!

Categories: C++ Tags:
  1. Jozsef Nyulas
    November 8, 2021 at 11:00

    it’s a good explanation. just to let you know the bitset examplet is okay, but the syntax at the
    int v = 0x12345678;
    std::cout << std::bitset(v); is the other way around, cout << bitset(32); 😀 took me a while to figure out why wasn’t working for me.

  2. January 27, 2020 at 22:50

    BOOOH!
    not using data words, unsign or format string.
    here:

    int getValuePNTR(const char* memory, int &start, int size)
    {
    DWORD retVal = 0;

    //now just add up array fields
    for (int i = start + size-1,j = size-1; j >= 0; –j, i–)
    {
    //fprintf(stdout, “\ncycle: %d, memory: [%x]”, j, memory[i]);

    if ((unsigned char)memory[i] == 00 && j > 0)
    retVal <<= 8;
    else
    retVal |= ((unsigned char)(memory[i]) << (8 * j));
    }
    //get the next field after this one
    start += size;
    return retVal;
    }

    call:

    fprintf(stdout, "\n[DWORD] LoaderFlag (zeroVal) :0x%08x", getValuePNTR(fileContent, readPointer, DWORD_L));

    • January 30, 2020 at 20:34

      This code automatically assumes the size of a unit of memory. The two assignments to retVal should replace 8 with sizeof(char). The function signature should also replace const char* with const unsigned char* for consistency and to allow you to remove the two unnecessary casts in the inner loop.

      😂

  3. jackson
    January 23, 2019 at 23:05

    So simple to understand the concept of left and right shifting now. Thanks! 😀

  4. mark
    July 23, 2017 at 08:39

    it helps me =) Thanks =)

  5. February 14, 2017 at 00:41

    Thank you! It was really helpful! 🙂

  6. Peter Harding
    December 4, 2016 at 04:50

    Thanks!!

  7. Jacek Rużyczka
    November 9, 2016 at 23:13

    Thank you for your hint! I’m currently struggling with the SPI interface of my Raspi and found out that the bit-endianness (MSB first vs. LSB first) was the problem, so I employed this algo to reverse all the data to get it LSB first: http://stackoverflow.com/questions/2602823/in-c-c-whats-the-simplest-way-to-reverse-the-order-of-bits-in-a-byte

    To test this algo, I used your code snippet, and yaaaay, everything works just as it should! *_*

  8. Donald
    May 6, 2016 at 11:33

    Thanks that’s really useful.

  9. fdssdf
    March 13, 2016 at 13:37

    bitset obitset.h is not found when I compile

  10. sam
    February 16, 2016 at 13:11

    what do I do if I want to write these numbers in a text file??

  11. Theko
    December 10, 2014 at 06:13

    I have to say that I have been impressed. A very nice tip this page is.

  12. Perseus Zepos
    March 7, 2014 at 19:50

    I’m always dumping binary numbers, and bitset is much cleaner than the looping method. Very nice!

  1. June 21, 2023 at 08:37
  2. December 16, 2015 at 22:30
  3. August 25, 2014 at 05:33

Share your thoughts! Note: to post source code, enclose it in [code lang=...] [/code] tags. Valid values for 'lang' are cpp, csharp, xml, javascript, php etc. To post compiler errors or other text that is best read monospaced, use 'text' as the value for lang.

This site uses Akismet to reduce spam. Learn how your comment data is processed.