简体   繁体   中英

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.

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);
}

From the doc of the std::bitset constructor :

If the value representation of val is greater than the bitset size, only the least significant bits of val are taken into consideration.

So another solution could be:

#include <iostream>

int main() {
    std::bitset<16> myBits16(0b0110110001111101);
    std::bitset<8> myBits8(myBits16.to_ulong());
    char reg = static_cast<char>(myBits8.to_ulong());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM