C++:如何获取 Bitset 的 MSB(最高有效位)(使用按位运算符)?

C++: How to get the MSB (Most-Significant Bit) of a Bitset (using bitwise operators)?

我正在尝试将十进制数转换为长度为 27 的位集,然后使用按位运算符从该位集中检索 MSB(最左边的位)。例如,数字67108865表示为100000000000000000000000001,MSB为1。又如数字1表示为000000000000000000000000001,MSB为0.

下面是我的 C++ 代码:

unsigned int value = 67108865;
bitset<27> bs(value);
int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;
cout << most_significant_bit << endl;

但是,我收到以下错误:

error: no match for ‘operator&’ (operand types are ‘std::bitset<27>’ and ‘int’) int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;

如何使用按位运算符检索 MSB?

这会让你得到最重要的一点:

auto msb = bs[bs.size()-1];

要使用按位运算符执行此操作,您需要首先使用 to_ulong() or unsigned long long using to_ullong():

将位集转换为 unsigned long
auto msb = bs.to_ulong() >> (bs.size() - 1);

只需使用 operator[] 获取最高有效位。

bitset<27> bs(value);
int ms_bit = bs[bs.size()-1];