Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
user489041 Avatar asked Nov 08 '11 16:11

user489041


People also ask

Which bit is set?

Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0's and 1's. So, the digit 1 is known as set bit in the terms of the computer.

How do you set a specific bit?

Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.

Which operator is used to check if a particular bit is on or off?

Bitwise AND operation is used to check whether a particular bit is on or off.


1 Answers

You can use the bitwise & operator:

int value = 0x102F1032;
int checkBit = 0x00010000;
bool hasBit = (value & checkBit) == checkBit;
like image 144
Matt DeKrey Avatar answered Oct 10 '22 11:10

Matt DeKrey