∟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:

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

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 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

 Reference Data Types and Variables

 Enum Types and Enum Constants

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 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

 Assert Statements and -ea" Option

 Annotation Statements and Declarations

 Java Related Terminologies

 Archived Tutorials

 References

 Full Version in PDF/EPUB