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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With