If I have the decimal 12
, its representation in binary is 00001100
. How do I extract the fifth bit, which in this case is 1
? I tried shifting left by 4
and AND
-ing with 1
but this is not correct. Can someone tell me what I am doing wrong?
player = low << 4 & 1;
You actually want to obtain 3d bit (starting from the right end):
00001100
^
3d from the right end (bits are zero based)
All you have to do is to get rid of 3
lower bits (100
) with a help of >>
and check the next bit:
// 1 if 3d bit is set, 0 otherwise
player = (low >> 3) & 1;
Or if you have number 5
- index from the left end and assuming low
being byte
:
player = (low >> (sizeof(byte) * 8 - 5)) & 1;