6

I'm trying to initialize a std::bitset<256> at compile time with some of its indices, lets say 50-75 and 200-225 set to 1.

Based on http://en.cppreference.com/w/cpp/utility/bitset/bitset It looks like my 2 options are:

constexpr bitset();
constexpr bitset( unsigned long long val ); 

Could someone shed light on how I would initialize my bitset considering the second constructor wouldn't work for large indices?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Mozbi
  • 1,399
  • 1
  • 17
  • 25

2 Answers2

1

Bitset constructor constexpr bitset( unsigned long long val ) is limited in the sense that it cannot pre-set bits from position 64 upwards (as unsigned long long is a 64 bit value). Any bit higher than 64 will be initialized with 0, as the following example shows (cf. bitset constructors):

std::bitset<70> bl(ULLONG_MAX); // [0,0,0,0,0,0,1,1,1,...,1,1,1] in C++11

If you want to initialize also the higher bits in the constructor, I think you won't get around to use an initializer of type string or char*, i.e. bitset constructors of type (3) or (4).

Of course, for a bitset of length 256, the initializer string gets long:

std::bitset<256> myBitset("111100000011111000001110000010101000100000100010010000100000000001111");
// I did not count the digits...
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • 2
    note that [the constructor receiving `const char*` **doesn't have `constexpr`](https://en.cppreference.com/w/cpp/utility/bitset/bitset) – phuclv Apr 28 '21 at 10:32
0

You can use the constructor that takes a string as an argument and initialize it that way.

For example. the following line, will initialize b with 0000000101111001:

std::bitset<16> b (std::string("0101111001"));
Vivek
  • 320
  • 1
  • 5