4

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.

Seb
  • 410
  • 1
  • 6
  • 20

1 Answers1

7

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.

Dmitry
  • 13,797
  • 6
  • 32
  • 48