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.
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
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.to get the nth bit in integer
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.In Java the following works fine:
value
andx
can beint
orlong
(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 tovalue << (~x & 31)
(orvalue << (~x & 63)
ifvalue
islong
).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).