Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::bitset constexpr >64bit value

Tags:

c++

bitset

I want to have a bitset constexpr variable in my program. bitset can have unsigned long long value as a constructor which is 64bit value, I need 100 bit value. As per this Q&A, we can use constructor that takes a string as an argument and initialize it that way, but it won't be constexpr value. Is there any possible way?

like image 835
Taher Kawantwala Avatar asked Feb 20 '26 15:02

Taher Kawantwala


1 Answers

the constructor std::bitset<N>(uint64_t) is the only useful constexpr callable constructor here:

constexpr bitset(unsigned long long _Val) noexcept : _Array{static_cast<_Ty>(_Need_mask ? _Val & _Mask : _Val)} {}

and that will only provide 64 bits of information.

But since it is possible to initalize a std::bitset at compile time with another std::bitset, in theory you could make a constexpr function that initializes a std::bitset and returns that, like this:

template<size_t N>
constexpr std::bitset<N> make_bitset(const char* x) {
    std::bitset<N> result;

    for (int i = 0; x && x[i] != '\0'; ++i) {
        result.set(i, x[i] - '0');
    }

    return result;
}

sadly this doesn't compile as std::bitset<N>::set is not declared constexpr. But looking at the set function, in theory this function could be declared constexpr:

bitset& _Set_unchecked(size_t _Pos, bool _Val) noexcept { // set bit at _Pos to _Val, no checking
    auto& _Selected_word = _Array[_Pos / _Bitsperword];
    const auto _Bit      = _Ty{1} << _Pos % _Bitsperword;
    if (_Val) {
        _Selected_word |= _Bit;
    } else {
        _Selected_word &= ~_Bit;
    }

    return *this;
}

but until then, you can't initialize a std::bitset with more than 64 bits of information at compile time.

like image 198
Stack Danny Avatar answered Feb 22 '26 05:02

Stack Danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!