Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

C++ primer 5th edition: A bitset to represent a sequence of integers

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?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...