Hassingard
Hassingard

Reputation: 108

How to store randomly generated unsigned int numbers in a bitset

I have a bitset in which I need to store a # of randomly generated integers (store its bit representation of course). So, the thing is that I am confuse on how to do that.

i.e suppose that I generate the integers (all unsigned int) 8, 15 , 20, one at a time. How can I store the recently generated integer in my existing bit set.

Say that I start by generating "8" and store in the bitset, then I generate "15" and store it in the bitset.

I don't know or don't understand how to store those values within the bitset.

Note: I know in advance the size of the bitset, the size is based on the number of integers that I am going to generate, and that I know too. So, at the end what I need is a bitset with all the bits set matching the bits of all the generated integers.

I'll Appreciate your help.

Upvotes: 1

Views: 322

Answers (1)

R Sahu
R Sahu

Reputation: 206577

How can I store the recently generated integer in my existing bit set.

You can generate a temporary bitset form the integer and then assign values between the two bitsets.

Example program:

#include <iostream>
#include <bitset>
#include <cstdlib>

int main()
{
   const int size = sizeof(int)*8;
   std::bitset<2*size> res;
   std::bitset<size> res1(rand());
   std::bitset<size> res2(rand());

   for ( size_t i = 0; i < size; ++i )
   {
      res[i] = res1[i];
      res[size+i] = res2[i];
   }

   std::cout << "res1: " << res1 << std::endl;
   std::cout << "res2: " << res2 << std::endl;
   std::cout << "res: " << res << std::endl;

   return 0;
}

Output:

res1: 01101011100010110100010101100111
res2: 00110010011110110010001111000110
res: 0011001001111011001000111100011001101011100010110100010101100111

Update

A function to set the bitset values given an integer can be used to avoid the cost of creating temporary bitsets.

#include <iostream>
#include <bitset>
#include <cstdlib>
#include <climits>

const int size = sizeof(int)*8;

void setBitsetValue(std::bitset<2*size>& res,
                    int num,
                    size_t bitsetIndex,
                    size_t numIndex)
{
   if ( numIndex < size )
   {
      res[bitsetIndex] = (num >> numIndex) & 0x1;
      setBitsetValue(res, num, bitsetIndex+1, numIndex+1);
   }
}

int main()
{
   std::bitset<2*size> res;
   int num1 = rand()%INT_MAX;
   int num2 = rand()%INT_MAX;
   std::bitset<size> res1(num1);
   std::bitset<size> res2(num2);

   std::cout << "res1: " << res1 << std::endl;
   std::cout << "res2: " << res2 << std::endl;

   setBitsetValue(res, num1, 0, 0);
   setBitsetValue(res, num2, size, 0);

   std::cout << "res:  " << res << std::endl;

   return 0;
}

Upvotes: 2

Related Questions