I am asked on C++ primer 5th edition this exercise:
Exercise 17.10: Using the sequence 1, 2, 3, 5, 8, 13, 21, initialize a
bitset
that has a1
bit in each position corresponding to a number in this sequence. Default initialize anotherbitset
and write a small program to turn on each of the appropriate bits.
In fact I almost solved all the exercises of the book but I couldn't understand this. I've understood std::bitset
.
I've found a solution like this:
// init from the sequence: 1, 2, 3, 5, 8, 13, 21
std::bitset<22> bitseq("1000000010000100101110");
std::cout << bitseq << std::endl;
// Default initialize, then turn on.
std::bitset<22> bit_default;
for (auto i : {1, 2, 3, 5, 8, 13, 21})
bit_default.set(i);
std::cout << bit_default << std::endl;
assert(bitseq == bit_default);
But I don't know how it is this way and how it works? please help me to understand this if it is correct. Thanks guys too much!
I don't understand how can such 1000000010000100101110
represent the sequence 1, 2, 3, 5, 8, 13, 21
?.
How can 1000000010000100101110 represent the sequence 1, 2, 3, 5, 8, 13, 21?
Numbers in base 2 are typically written MSB first - most significant bit first - and typically numbered or indexed from right to left, from the least significant bit, starting from 0 (or 1).
1000000010000100101110
^ ^ ^-- bit with index 0 - least significant bit 2^0
^ ^ ^--- bit with index 1
^ ^ ^---- bit with index 2
^ ^ ^----- bit with index 3
^ ^ ^------ bit with index 4
^ ^ ^------- bit with index 5
^ ^ ^-------- bit with index 6
^ ^ ^--------- bit with index 7
^ ^--------------- bit with index 13
^----------------------- bit with index 21 - most significant bit 2^21
When numbering bit positions starting from 0 from the right side, the sequence 1, 2, 3, 5, 8, 13, 21
represents set bits within the string 1000000010000100101110
.