1

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
Nicole
  • 37
  • 4

2 Answers2

0

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;}
}
DrSvanHay
  • 1,170
  • 6
  • 16
  • Okay except that your solution does not output what the person asking exampled...yours outputs 0b0000 0000 1111 1111 while the person asking apparently wants 0b0000 0000 0000 0001 :) – Dr t Sep 16 '17 at 22:11
  • I think your comment was not for real, was it? But ok, I edited the example anyway. – DrSvanHay Sep 16 '17 at 22:22
  • DrSvanHay not for real at all...except for the sarcasm and the happy face – Dr t Sep 16 '17 at 22:24
0

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;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • 1
    Okay except that your solution does not output what the person asking exampled....Your solution outputs 0b0101 0101 0111 1010 while the person asking apparently wants 0b0000 0000 0000 0001 :) – Dr t Sep 16 '17 at 22:15
  • 1
    @Drt no. This one is not okay, it prints the bits in the wrong order. – DrSvanHay Sep 16 '17 at 22:21
  • 1
    DrSvanHay ahhhhhhhhhh you are right!!! Ha ha. I got so excited to be sarcastic that I missed it!! :) – Dr t Sep 16 '17 at 22:27
  • Ah yes. That is much better. Guess I missed a golden opportunity to edit. – Dr t Sep 16 '17 at 22:37