2

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Julian
  • 81
  • 1
  • 11

3 Answers3

3

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
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.

Sathish Guru V
  • 1,417
  • 2
  • 15
  • 39
0

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 decimals.

oerkelens
  • 5,053
  • 1
  • 22
  • 29