Warm tip: This article is reproduced from stackoverflow.com, please click
bit bit-manipulation byte c#

how do I extract the 5th bit of a byte in c#

发布于 2020-05-13 12:40:11

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;
Questioner
Julian
Viewed
27
Dmitry Bychenko 2020-02-28 16:25

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;