Search code examples
c++bitset

bitset and numerical sequence C++


Im learning C++ at the minute with book by Stanley Lippman. Im studying paragraph that named "class Bitset". There is an exercise where he gives me numerical sequence to transfrom into bitset<32>.

The numerical sequence is: 1,2,3,5,8,13,21. Can i ask you is my code right for peresenting this numerical sequence? Lippman also want me to use each bit in bitset to represent sequence, but is bitset can store more than 1 value in it? Im doing it first time and the only idea i got is:

int index = 0;
const int size_ = 7;
unsigned long f2[size_];

int main()
{
   setlocale(LC_ALL,"rus");

   string try1;

   cout << "Type your numerical sequence in binary code: " << endl;

      while (cin >> try1) {

         bitset<32> go(try1);

         if ( go.to_ulong() > 21 )  { cout << "End of sequence" << endl; break; }        

         f2[index] = go.to_ulong();

         index++;

         try1.clear();

         go.reset();
       }

   for ( index; index >= 0; index-- ) {
       cout << f2[index] << " ";
   }

   system("pause");

   return 0;
}

Solution

  • is bitset can store more than 1 value in it?

    Well, yes — it's a set of bits, hence the name. Each bit can be on or off, which may be deemed one "value". Thus, a std::bitset<32> can encode 32 "values" inside it. Ultimately, the whole bitset itself has only one value at a time, but that's the beauty of "encoding" data — every value is composed of smaller building blocks. To solve this problem, you need to remember that every value stored on your computer consists of a series of bits.

    Presumably you are supposed to encode the sequence x,y,...,z by setting bits at positions x,y,...,z. For that you may use the function set.

    For example, once you've set bits 1,2,3,5,8,13,21 (and I'm assuming a 0-based system here so that you can support the input 0), your bitset will "contain":

    #0   #4   #8   #12  #16  #20  #24  #28  #32
    +----+----+----+----+----+----+----+----+
    |0111 0100 1000 0100 0000 0100 0000 0000|
    +-^^^+-^--+^---+-^--+----+-^--+----+----+
      |||  |   |     |         |
    

    When translated from binary to decimal, this sequence is the number ‭1,954,808,832‬, which is exactly what you'll get if you then call to_ulong() on the bitset object.

    In your code, you're instead creating a fresh bitset for each value entered, which is useless; your actual storage is just an array of unsigned long, which is not in keeping with the spirit of the exercise (which is to use bitset for storage instead). You're also calling reset() just before the object goes out of scope (at the end of the loop body), which does nothing.