Using Bitset to display 16 bits into four groups of 4 bits in C++

1.8k views Asked by At

I'm working on a programming assignment and I am using the bitset<> function in C++ to print put the binary representation of an integer by 16 bits. I am having a hard time trying to print the 16 bits into four groups of four bits with a space in between. How can I do that with a bitset function?

cout << "0b" << bitset<16>(integer) << "\t";

This prints out if the integer was 1

0b0000000000000001

What i am trying to print out is

0b0000 0000 0000 0001
2

There are 2 answers

3
DrSvanHay On

You could implement a filtering stream, but why not keep it simple?

auto the_number = std::bitset<16>(1);

std::cout << "0b";
int count = 0;
for(int i=the_number.size()-1; i>=0; i--)
{
    std::cout << std::bitset<16>(255)[i];
    if(++count == 4) {std::cout << " "; count = 0;}
}
4
Stephan Lechner On

The <<-operator for bitsets does not provide a format specifier that separates the nibbles. You'll have to iterate through the bits on your own and introduce separators "manually":

int main() {

    int integer = 24234;
    bitset<16> bits(integer);
    cout << "0b";
    for (std::size_t i = 0; i < bits.size(); ++i) {
        if (i && i%4 == 0) { // write a space before starting a new nibble (except before the very first nibble)
            cout << ' ';
        }
        std::cout << bits[bits.size() - i - 1];
    }
    return 0;
}