Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking individual bits in a byte array in Java?

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!

like image 924
r123454321 Avatar asked Sep 21 '13 09:09

r123454321


1 Answers

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.

like image 118
Rohit Jain Avatar answered Sep 19 '22 13:09

Rohit Jain