简体   繁体   中英

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

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;

You need to left shift the One and & with your variable.

player = (1 << 4) & low;

This will give you the 5th binary digit with trailing zeros.

player = ((1 << 4) & low) >> 4;

This gives the exact 5th binary Digit, removing the Trailing Zeros.

Instead of shifting bits, you can simply use a bitwise AND. As others said, you are looking at the 3rd bit from the right (zero-based), in other words, at the bit that represents 2^3.

player = (low & 8) / 8;

A more generic solution would be

private int GetBit(int number, int bit) => (number & (1 << bit)) / (1 << bit);

Note: This does require casting your decimal to int since & doesn't work with decimal s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM