Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

getBit() - Retrieving a Bit from a Byte Array

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:

valByte   : ???????? ???????? ???????? xxyxxxxx
>> 5
-----------------------------------------------
          = ???????? ???????? ???????? ?????xxy
& 0x0001  : 00000000 00000000 00000000 00000001
-----------------------------------------------
          = 00000000 00000000 00000000 0000000y

Sections in This Chapter

setBit() - Storing a Bit into a Byte Array

getBit() - Retrieving a Bit from a Byte Array

rotateLeft() - Left Rotating All Bits in a Byte Array

bitStringTest.java - Testing Program

Dr. Herong Yang, updated in 2008
getBit() - Retrieving a Bit from a Byte Array