[英]C++: How to get the MSB (Most-Significant Bit) of a Bitset (using bitwise operators)?
I am trying to convert a decimal number to a bitset of length 27
and then retrieve the MSB (left-most bit) from that bitset using bitwise operators.我正在尝试将十进制数转换为长度为
27
的位集,然后使用按位运算符从该位集中检索 MSB(最左边的位)。 For example, the number 67108865
is expressed as 100000000000000000000000001
and the MSB is 1
.例如,数字
67108865
表示为100000000000000000000000001
并且 MSB 为1
。 Another example is the number 1
which is expressed as 000000000000000000000000001
and the MSB is 0
.另一个例子是数字
1
,表示为000000000000000000000000001
,MSB 为0
。
Below is my C++ code:下面是我的 C++ 代码:
unsigned int value = 67108865;
bitset<27> bs(value);
int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;
cout << most_significant_bit << endl;
However, I receive the following error:但是,我收到以下错误:
error: no match for 'operator&' (operand types are 'std::bitset<27>' and 'int') int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;
错误:“operator&”不匹配(操作数类型为“std::bitset<27>”和“int”) int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;
How would I retrieve the MSB using bitwise operators?如何使用按位运算符检索 MSB?
Just use the operator[]
to get the most significant bit.只需使用
operator[]
即可获得最高有效位。
bitset<27> bs(value);
int ms_bit = bs[bs.size()-1];
This would get you the most significant bit:这会让你得到最重要的一点:
auto msb = bs[bs.size()-1];
To do it using bitwise operators you need to first convert the bitset to an unsigned long
usingto_ulong()
or unsigned long long
using to_ullong()
:要使用按位运算符执行此操作,您需要首先使用 to_ulong() 将 bitset 转换为
unsigned long
或使用to_ullong()
to_ulong()
将unsigned long long
转换为:
auto msb = bs.to_ulong() >> (bs.size() - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.