How to get the value of a bit at a certain positio

2019-01-14 00:36发布

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 byte bit
4条回答
家丑人穷心不美
2楼-- · 2019-01-14 00:59

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.

查看更多
ら.Afraid
3楼-- · 2019-01-14 01:08

to get the nth bit in integer

 return ((num >> (n-1)) & 1);
查看更多
萌系小妹纸
4楼-- · 2019-01-14 01:11
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.
查看更多
Root(大扎)
5楼-- · 2019-01-14 01:14

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

查看更多
登录 后发表回答