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

JavaByteBit

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

to get the nth bit in integer

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

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGlen654View Question on Stackoverflow
Solution 1 - JavaHunter McMillenView Answer on Stackoverflow
Solution 2 - JavaCharlie MartinView Answer on Stackoverflow
Solution 3 - Javasrc3369View Answer on Stackoverflow
Solution 4 - JavarslemosView Answer on Stackoverflow