This section provides a tutorial example on how to get one bit back from a byte array at a specific bit position - getBit().
2. getBit() - To get one bit back from a bit string stored in a byte array at the specified position:
private static int getBit(byte[] data, int pos) {
int posByte = pos/8;
int posBit = pos%8;
byte valByte = data[posByte];
int valInt = valByte>>(8-(posBit+1)) & 0x0001;
return valInt;
}
Explanations:
The method interface expects the caller to provide the byte array that stores the bit string,
the position in the bit string where bit value needs to be retrieved.
The first statement calculates the array index, "posByte", of the source byte that holds the bit to be retrieved.
The second statement calculates the bit position, "posBit", in the source byte where the bit value needs to be retrieved.
The third statement fetches the source byte into a temporary variable, "valByte".
The fourth statement gets the bit value from "valdByte" at the bit position of "posBit".
To understand how the fifth statement works, let's assume that posBit = 2. Then the evaluation process of
the statement can be described as: