Search code examples
c++bitset

How to select first 8 bit from bitset<16> in c++?


I have a variable and it's type is bitset<16>. I want to get first 8 bit of my variable and put it into char variable. I know how to convert bitset to char, but I don't know how to select first 8 bit and convert it to char.


Solution

  • If by "first 8 bits" you're talking about 8-MSB, consider using the >> operator :

    #include <iostream>
    
    int main() {
        std::bitset<16> myBits(0b0110110001111101);
        char reg = 0;
    
        reg = static_cast<char>(myBits.to_ulong() >> 8);
    }