How to get the value of a bit at a certain position from a byte?
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.
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.