1

Is there a way of performing bitwise operations on two std::bitsets of different sizes?

Something similar to this:

    std::bitset<8> payload { 0b1010'0010 };
    std::bitset<10> segment { 0b00'0000'0000 };
    segment |= payload;

For the above example, I basically want to transfer all the 8 bits of payload to the lower bits of segment. What other options do I have if this cannot be done? Should I write a for loop that uses the subscript operator[] to transfer the bits one by one?

digito_evo
  • 3,216
  • 2
  • 14
  • 42
  • @Captain Obvlious I took a brief look at it. Didn't find anything relevant. Also, I tried std::ranges::copy but that doesn't work since std::bitset does not support iterators?? – digito_evo Dec 19 '22 at 18:35
  • @CaptainObvlious you cannot (easily) get iterator from `std::bitset`, as OP said. – apple apple Dec 19 '22 at 18:41
  • If you're only using "small" bitsets, you could use [`to_ullong`](https://en.cppreference.com/w/cpp/utility/bitset/to_ullong) and use normal bit-twiddling and assign the result back. – Ted Lyngmo Dec 19 '22 at 18:43
  • 1
    @Ted Lyngmo Yes I guess I'm using small bitsets, maybe max 16 bits. Sounds like a good idea. I'll try ulong. – digito_evo Dec 19 '22 at 18:46
  • 1
    use `to_ullong` to convert the smaller bitset to the bigger one, then use `|=` – 463035818_is_not_an_ai Dec 19 '22 at 18:47
  • 1
    Have a look at [bitset2](https://github.com/ClaasBontus/bitset2/). It supports conversion from one type of bitset2 to another. – Claas Bontus Dec 20 '22 at 07:39

1 Answers1

3

Convert the narrower to the wider one then you can use |=:

#include <iostream>
#include <bitset>

int main() {
    std::bitset<8> payload { 0b1010'0010 };
    std::bitset<10> segment { 0b00'0000'0000 };
    
    std::bitset<10> x(payload.to_ullong());
    segment |= x;
    std::cout << segment;
}

For wider ones you can use to_string and the constructor creating the bitset from a string.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185