0

I am using a big number (over 128 bits integer) in my code. I find that c++ have std::bitset to simple some operation so I don't have to break my data into several integers. But I soon find another issue, if I have to convert several (long) integers into bitset, what's the best way to do that? For example, I am trying to convert four long integers (each of 32bits) to a 128bit bitset, the following way doesn't work because for each integers (the shift operation will only work for shifted bits less than 32)

std::bitset<256> b;
unsigned long v1=2, v2=9, v3=19, v4=1021;
b |= v1 | (v2<<32) | (v3<<64) | (v4<<128);

Now I use a for loop to set each bit on the bitset but I am looking for a more efficient and elegant way to do so.

user1285419
  • 2,183
  • 7
  • 48
  • 70
  • Partial answer, so I'm leaving a comment only. There are some bigint libraries out there that could be useful. For example: https://mattmccutchen.net/bigint/ – MPelletier Apr 15 '12 at 03:42

2 Answers2

2

This might not be the best option, but what about this?

typedef std::bitset<256> bs256;
b |= bs256(v1) | (bs256(v2) << 32) | (bs256(v3) << 64) | (bs256(v4) << 128);
touko
  • 410
  • 4
  • 7
0

I think you may have to live with setting them bit by bit in a loop:

int v[4]; //< keep your bitmasks in an array
int nbits = 8 * sizeof(v[0]);
for(int i = 0; i < 128; ++i) {
  int t = v[i / nbits];
  bit.set(i, t & (1 << (i % nbits)));
}

An alternative is for you to derive a class from bitset that could set not just individual bits, but entire bitsets at arbitrary positions.

George Skoptsov
  • 3,831
  • 1
  • 26
  • 44