6

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!

Jesper
  • 202,709
  • 46
  • 318
  • 350
r123454321
  • 3,323
  • 11
  • 44
  • 63
  • Possible duplicate of [How to get the value of a bit at a certain position from a byte?](https://stackoverflow.com/questions/9354860/how-to-get-the-value-of-a-bit-at-a-certain-position-from-a-byte) – Martin Schröder May 29 '17 at 14:08
  • @MartinSchröder first - necroposting, second - no, it's definitely different, here he requires byte[] – Andrii Plotnikov Nov 23 '17 at 14:57

1 Answers1

20

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525