如何检查 C# 中是否设置了特定位
在 C# 中,我有一个 32 位值,我将其存储在 int 中。我需要查看是否设置了特定位。我需要的位是0x00010000
。
我想出了这个解决方案:
这就是我正在寻找的:
Hex: 0 0 0 1 0 0 0 0 0 Binary 0000|0000|0000|0001|0000|0000|0000|0000|0000
所以我向右位移 16,这会给我:
Hex: 0 0 0 0 0 0 0 0 1 Binary 0000|0000|0000|0000|0000|0000|0000|0000|0001
然后我向左位移 3,这会给我:
Hex: 0 0 0 0 0 0 0 0 8 Binary 0000|0000|0000|0000|0000|0000|0000|0000|1000
然后我将 32 位值转换为一个字节,并查看它是否等于 8。
所以我的代码将是这样的:
int value = 0x102F1032;
value = value >> 16;
byte bits = (byte)value << 3;
bits == 8 ? true : false;
是否有一种更简单的方法来检查是否设置了特定位而不进行所有移位?
In C#, I have a 32 bit value which I am storing in an int. I need to see if a particular bit is set. The bit I need is 0x00010000
.
I came up with this solution:
Here is what I am looking for:
Hex: 0 0 0 1 0 0 0 0 0 Binary 0000|0000|0000|0001|0000|0000|0000|0000|0000
So I right bit shift 16, which would give me:
Hex: 0 0 0 0 0 0 0 0 1 Binary 0000|0000|0000|0000|0000|0000|0000|0000|0001
I then bit shift left 3, which would give me:
Hex: 0 0 0 0 0 0 0 0 8 Binary 0000|0000|0000|0000|0000|0000|0000|0000|1000
I then case my 32 bit value to a byte, and see if it equals 8.
So my code would be something like this:
int value = 0x102F1032;
value = value >> 16;
byte bits = (byte)value << 3;
bits == 8 ? true : false;
Is there a simpler way to check if a particular bit is set without all the shifting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
如果你不喜欢位掩码方法:(
我可能得到了错误的计数,它不是你正在寻找的 21)
对于只有 32 位的情况,这可能有点滥用,但如果你需要使用更长的位数组,这会更清晰。
And if you don't like the bit mask approach:
(I may have got the wrong count and it's not 21 you are looking for)
This might me a bit abusive for a case where you only have 32 bits, but if you need to work with longer bit arrays this is much clearer.
你可以说:
you can say:
如果答案非零,则将其与移位后的值一起设置位。
如果您要进行大量操作,请使用常量 (1 << BitToTest),如果进行很多操作但位不同,则使用静态数组来查找 2 ^ BitToTest。
And it with the shifted value, bit is set if the answer is nonzero.
If you are doing one bit a lot use a constant for (1 << BitToTest), if a lot but different bits, a static array to look up 2 ^ BitToTest.
此外,但也许不是更好,您可以使用 BitVector32 结构。
Additionally, but maybe not better you can use the BitVector32 structure.
您可以使用按位 &操作员:
You can use the bitwise & operator:
这比那容易得多。只需使用按位
AND
运算符,如下所示It's much easier than that. Just use the bitwise
AND
operator like this你可以像这样检查:
You can just check like so:
您只需执行按位与即可。
You can just do a bitwise AND.
使用按位与运算符
&
:Use the bitwise and operator
&
: