在Java中如何检查字节数组中的单个位?

6
假设我有一个字节数组,并且我有一个函数,用于检查字节数组中第n位最不重要的比特位索引是1还是0。如果该位为1,则函数返回true,否则返回false。字节数组的最不重要的比特位定义为字节数组的第0个索引中的最后一个比特位,而字节数组的最重要的比特位定义为字节数组长度减1的索引中的最重要的比特位。
例如,
byte[] myArray = new byte[2];
byte[0] = 0b01111111;
byte[1] = 0b00001010;

调用:

myFunction(0) = true;
myFunction(1) = true;
myFunction(7) = false;
myFunction(8) = false;
myFunction(9) = true;
myFunction(10) = false;
myFunction(11) = true;

什么是最佳的方法来实现这个?谢谢!

可能是重复的问题,参考如何从字节中获取特定位置的位的值? - Martin Schröder
@MartinSchröder 首先,这是个 “necroposting”(即回复了很早以前的帖子),其次,不,它绝对不同,在这里他需要 byte[]。 - Andrii Plotnikov
1个回答

20
你可以使用这个方法:
public boolean isSet(byte[] arr, int bit) {
    int index = bit / 8;  // Get the index of the array for the byte with this bit
    int bitPosition = bit % 8;  // Position of this bit in a byte

    return (arr[index] >> bitPosition & 1) == 1;
}

bit % 8 是相对于一个 byte 的比特位位置。
arr[index] >> bit % 8 将位于 index 的比特位移动到位置0。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接