Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中检查字节数组中的单个位?_Java_Bit Manipulation - Fatal编程技术网

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

在Java中检查字节数组中的单个位?,java,bit-manipulation,Java,Bit Manipulation,假设我有一个字节数组,我有一个函数检查字节数组的第n个最低有效位索引是1还是0。如果位为1,则函数返回true;如果位为0,则函数返回false。字节数组的最低有效位定义为字节数组第0个索引中的最后一个有效位,字节数组的最高有效位定义为字节数组第(byte array.length-1)个索引中的最高有效位 比如说, byte[] myArray = new byte[2]; byte[0] = 0b01111111; byte[1] = 0b00001010; 电话: myFunction(

假设我有一个字节数组,我有一个函数检查字节数组的第n个最低有效位索引是1还是0。如果位为1,则函数返回true;如果位为0,则函数返回false。字节数组的最低有效位定义为字节数组第0个索引中的最后一个有效位,字节数组的最高有效位定义为字节数组第(byte array.length-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;
最好的方法是什么


谢谢

您可以使用以下方法:

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;
}
位%8
是相对于
字节的位位置

arr[index]>>位%8
索引处的位移动到位0位置

@MartinSchröder first-necropposting,second-no的可能重复项,绝对不同,这里他需要字节[]