0

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 a 1 bit in each position corresponding to a number in this sequence. Default initialize another bitset 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?.

Maestro
  • 2,512
  • 9
  • 24

1 Answers1

2

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • So I can start from `1` rather than `0` to be something like this `100000001000010010111`? – Maestro Jan 12 '21 at 21:05
  • 1
    Let's a real life example: When you __index__ the number of shoes, in real life you count: 1st shoe. 2nd shoe. 3rd shoe. In programming arrays start from 0: shoe __number 0__ is the first shoe, shoe _number_ 1 is the second shoe, etc. You can __index__ the bit positions starting from 1, but usually it's confusing, as array indexing starts from 0, and bitshifts work like `1<<4` is the 5th (not 4rd!) bit from the right. – KamilCuk Jan 12 '21 at 21:07