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

110,280

Solution 1

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.

Solution 2

You want to make a bit mask and do bitwise and. That will end up looking very close to what you have -- use shift to set the appropriate bit, use & to do a bitwise op.

So

 return ((byte)ID) & (0x01 << pos) ;

where pos has to range between 0 and 7. If you have the least significant bit as "bit 1" then you need your -1 but I'd recommend against it -- that kind of change of position is always a source of errors for me.

Solution 3

to get the nth bit in integer

 return ((num >> (n-1)) & 1);

Solution 4

In Java the following works fine:

if (value << ~x < 0) {
   // xth bit set
} else {
   // xth bit not set
}

value and x can be int or long (and don't need to be the same).

Word of caution for non-Java programmers: the preceding expression works in Java because in that language the bit shift operators apply only to the 5 (or 6, in case of long) lowest bits of the right hand side operand. This implicitly translates the expression to value << (~x & 31) (or value << (~x & 63) if value is long).

Javascript: it also works in javascript (like java, only the lowest 5 bits of shift count are applied). In javascript any number is 32-bit.

Particularly in C, negative shift count invokes undefined behavior, so this test won't necessarily work (though it may, depending on your particular combination of compiler/processor).

Share:
110,280
Glen654
Author by

Glen654

Updated on July 09, 2022

Comments

  • Glen654
    Glen654 almost 2 years

    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.

  • Charlie Martin
    Charlie Martin over 12 years
    Actually, that's bitwise and; logical and is &&.
  • Hunter McMillen
    Hunter McMillen almost 6 years
    I would argue that the parentheses in fact make this code clearer, not everyone has the precedence table memorized.