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

20,455

Solution 1

You can use the bitwise & operator:

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

Solution 2

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

(value & 0x00010000) != 0

Solution 3

You can just check like so:

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

Solution 4

Use the bitwise and operator &:

return (value & 0x100000) != 0;

Solution 5

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.

Share:
20,455
user489041
Author by

user489041

Updated on July 09, 2022

Comments

  • user489041
    user489041 almost 2 years

    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?