55

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
Glen654
  • 1,102
  • 3
  • 14
  • 18
  • Your nearly there you just need to mask off the bit you have just shifted by ANDing with 0x01 – Dampsquid Feb 20 '12 at 00:42
  • Possible duplicate of [Java: Checking if a bit is 0 or 1 in a long](https://stackoverflow.com/questions/1092411/java-checking-if-a-bit-is-0-or-1-in-a-long) – Martin Schröder May 29 '17 at 14:10

4 Answers4

125
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.
Neeme Praks
  • 8,956
  • 5
  • 47
  • 47
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
10

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.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
3

to get the nth bit in integer

 return ((num >> (n-1)) & 1);
src3369
  • 1,839
  • 2
  • 17
  • 18
1

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

rslemos
  • 2,454
  • 22
  • 32