简体   繁体   中英

How to check if a particular bit is set in C#

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?

You can use the bitwise & operator:

int value = 0x102F1032;
int checkBit = 0x00010000;
bool hasBit = (value & checkBit) == checkBit;

It's much easier than that. Just use the bitwise AND operator like this

(value & 0x00010000) != 0

您可以像这样检查:

bool bitSet = (value & 0x10000) == 0x10000;

And if you don't like the bit mask approach:

int data = 0;

var bits = new BitArray(new int[] { data });

bits.Get(21);

(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 just do a bitwise AND.

int result = yourByte & 16;
if (result != 0)
{
    // do what you need to when that bit is set
}

使用按位和运算符&

return (value & 0x100000) != 0;

you can say:

if( (number & 0x00010000 ) != 0 )
{
  //the bit is set...
}
int someInt = 8;
int BitToTest = 3;
bool isSet = (someInt & (1 << BitToTest)) != 0;

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.

Additionally, but maybe not better you can use the BitVector32 structure.

int value =  0x102F1032;
var vector = new BitVector32(value);
return vector[0x1000]; //true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM