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! š
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));
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.
š
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.