如何在 C++ 中 select 来自 bitset<16> 的前 8 位?

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

我有一个变量,它的类型是 bitset<16>。我想获取变量的前 8 位并将其放入 char 变量中。我知道如何将 bitset 转换为 char,但我不知道如何 select 前 8 位并将其转换为 char。

如果 "first 8 bits" 你说的是 8-MSB,考虑使用 >> 运算符:

#include <iostream>

int main() {
    std::bitset<16> myBits(0b0110110001111101);
    char reg = 0;

    reg = static_cast<char>(myBits.to_ulong() >> 8);
}

来自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.

所以另一种解决方案可能是:

#include <iostream>

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