Check each bit in the byte array with Java?
•
Java
So I have a byte array, and I have a function to check whether the nth least significant bit index of the byte array is 1 or 0 If the bit is 1, it returns true. If the bit is false, 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) index of byte array
For example,
byte[] myArray = new byte[2]; byte[0] = 0b01111111; byte[1] = 0b00001010;
call:
myFunction(0) = true; myFunction(1) = true; myFunction(7) = false; myFunction(8) = false; myFunction(9) = true; myFunction(10) = false; myFunction(11) = true;
What's the best way to do this?
thank you!
Solution
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% 8 is the bit position relative to the byte Arr [index] > > bit% 8 moves the bit at the index to the 0 position
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码