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.
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!
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 a byte
.arr[index] >> bit % 8
moves the bit at index
to bit 0 position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With