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 int
s, 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!
I’m always dumping binary numbers, and bitset is much cleaner than the looping method. Very nice!
I have to say that I have been impressed. A very nice tip this page is.
what do I do if I want to write these numbers in a text file??
bitset obitset.h is not found when I compile
Thanks that’s really useful.
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! *_*
Thanks!!
Thank you! It was really helpful! 🙂
it helps me =) Thanks =)
So simple to understand the concept of left and right shifting now. Thanks! 😀