Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding whether bit position is set in C# [duplicate]

Tags:

c#

binary

bit

I'm getting quite confused here.

If I have a number, let's call it 16 here, and I want to check if a particular bit is set. I would do the following:

if (16 & (2 ^ bitPosition) == (2 ^ bitPosition))

Right?

Why then, for bitPosition = 2, is that statement returning true? Shouldn't it be false, as only bitPosition = 4 is true in that case?

My understanding was:

Bit|Val
0  |1
1  |2
2  |4
3  |8
4  |16
5  |32
6  |64
7  |128

I've never worked with this kind of thing before and it's baffling me.

like image 216
Seb Avatar asked Mar 13 '23 13:03

Seb


1 Answers

The ^ operator is bitwise XOR in C#.
Try to check as follows:

if ((value & (1 << bitPosition)) != 0)

Where << is a bit shift left operator that is, in fact, exponentiation of 2.

like image 199
Dmitry Avatar answered Mar 24 '23 23:03

Dmitry