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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18931283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:36:54  来源:igfitidea点击:

Checking individual bits in a byte array in Java?

javabit-manipulation

提问by r123454321

So say I have a byte array, and I have a function that checks whether the n-th least significant bit index of the byte array is a 1 or a 0. The function returns true if the bit is a 1 and false if the bit is a 0. The least significant bit of the byte array is defined as the last significant bit in the 0th index of the byte array, and the most significant bit of the byte array is defined as the most significant bit in the (byte array.length - 1)th index of the byte array.

所以说我有一个字节数组,我有一个函数来检查字节数组的第 n 个最低有效位索引是 1 还是 0。如果该位是 1,则该函数返回 true,如果该位为 false,则该函数返回是 0。字节数组的最低有效位定义为字节数组第 0 个索引中的最后一个有效位,字节数组的最高有效位定义为 (byte array. length - 字节数组的第 1) 个索引。

For instance,

例如,

byte[] myArray = new byte[2];
byte[0] = 0b01111111;
byte[1] = 0b00001010;

Calling:

调用:

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

What is the best way to do this?

做这个的最好方式是什么?

Thanks!

谢谢!

采纳答案by Rohit Jain

You can use this method:

您可以使用此方法:

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 % 8is the bit position relative to a byte.
arr[index] >> bit % 8moves the bit at indexto bit 0 position.

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