如何从字节中获取某个位置的位值?

如何从字节中获取某个位置的位值?

问题描述:

如果我有一个字节,该方法将如何在某个位置取回一个比特?

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));
}

其中ID是我要从中检索信息的字节的名称.

where ID is the name of the byte I am retrieving information from.

public byte getBit(int position)
{
   return (ID >> position) & 1;
}

按位置右移ID将使#position位在数字右侧最远的位置.将其与按位AND &与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.