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

Table of Contents

 About This Book

 Installing JDK 1.4 on Windows 2000

 Installing JDK 1.5 on Windows XP

 Installing JDK 1.6 on Windows XP

 Execution Process, Entry Point, Input and Output

 Bits, Bytes, Bitwise and Shift Operations

Managing Bit Strings in Byte Arrays

 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

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 References

 PDF Printing Version

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