use*_*041 11 c# bit-manipulation bit
在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;
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来检查是否在没有所有移位的情况下设置了特定位?
Mat*_*rey 15
您可以使用按位&运算符:
int value = 0x102F1032;
int checkBit = 0x00010000;
bool hasBit = (value & checkBit) == checkBit;
Run Code Online (Sandbox Code Playgroud)
Dav*_*nan 11
它比那容易得多.只需AND像这样使用按位运算符
(value & 0x00010000) != 0
Run Code Online (Sandbox Code Playgroud)
小智 4
您只需执行按位与即可。
int result = yourByte & 16;
if (result != 0)
{
// do what you need to when that bit is set
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16134 次 |
| 最近记录: |