0

A std::bitset isn't an integer, it's an array of bits. But when I initialize it with the bits in the correct order (as I would an array), it seems that all of the bits get reversed like an Endian swap.

The pattern I want is:

[1] 0 1  0  1  1  0  1  0  1  0  1  // [1] should be array Element[0].

I initialize with this:

std::bitset<12> bMyBitset("101011010101");

But when I use a function that prints out the array elements, I get this:

// Backwards:
[0] = 1, [1] = 0, [2] = 1, [3] = 0, [4] = 1, [5] = 0, [6] = 1, [7] = 1, [8] = 0, [9] = 1, [10] = 0, [11] = 1

What I want is this:

// Forward:
[0] = 1, [1] = 0, [2] = 1, [3] = 0, [4] = 1, [5] = 1, [6] = 0, [7] = 1, [8] = 0, [9] = 1, [10] = 0, [11] = 1

I know I can manually put all the bits backwards in the initializer string, but that is extremely tedious and error prone. I'm looking for a solution where I can put them in the same order that I would when initializing an array, with Element[0] first.

I want to do this:

std::bitset<12> bMyBitset {1,0,1,0,1,1,0,1,0,1,0,1};
// no matching function for call to 'std::bitset<12>::bitset(<brace-enclosed initializer list>)'

How can I initialize a bitset with elements in array order?

Nick
  • 10,904
  • 10
  • 49
  • 78
  • `[0]` is the rightmost bit of a bitset. – NathanOliver Sep 24 '21 at 20:34
  • `[0]` is the first element of an array. And if we think of a `bitset` as an array of booleans, there is no "right" or "left", only "first" and "last". "Right" and "left" only matter if you're trying to print out the set as a string or convert it to an integer. – Nick Sep 24 '21 at 20:48
  • A bitset isn't an array though. It's supposed to model a bit-feild, and in those cases, the 0-th bit is the LSB, or right most bit. https://en.wikipedia.org/wiki/Bit_numbering – NathanOliver Sep 24 '21 at 20:51
  • If you want a boolean array that takes advantage of bit packing, then `vector` will do that, and give you the semantics you want. It can be a pain to deal with though as `operator[]` returns proxy objects. – NathanOliver Sep 24 '21 at 20:53
  • "*`[0]` is the first element of an array*" - `std::map` would like to have a word with you :) – Fureeish Sep 24 '21 at 21:01
  • If you look at the value of a byte of memory as binary, say `01000001`, and you use that value to construct a `bitset`, what order would you expect the bits to be in? What value should `[0]` have? – 1201ProgramAlarm Sep 24 '21 at 21:23
  • I'm okay with `Element[0]` being the LSB as stored in the bitset and as displayed in `cout`, but for reasons of sanity, I'd like to *initialize* the bitset by specifying LSB first and MSB last, because that matches the pattern of the data the bitset represents. – Nick Sep 24 '21 at 21:58

0 Answers0