Printing numbers in binary format in C++
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:
at the top of your code.