How to get the value of a bit at a certain position from a byte?

Glen654 picture Glen654 · Feb 20, 2012 · Viewed 97.3k times · Source

If I have a byte, how would the method look to retrieve a bit at a certain position?

Here is what I have know, and I don't think it works.

public byte getBit(int position) {
    return (byte) (ID >> (position - 1));
}

where ID is the name of the byte I am retrieving information from.

Answer

Hunter McMillen picture Hunter McMillen · Feb 20, 2012
public byte getBit(int position)
{
   return (ID >> position) & 1;
}

Right shifting ID by position will make bit #position be in the furthest spot to the right in the number. Combining that with the bitwise AND & with 1 will tell you if the bit is set.

position = 2
ID = 5 = 0000 0101 (in binary)
ID >> position = 0000 0001

0000 0001 & 0000 0001( 1 in binary ) = 1, because the furthest right bit is set.