Java program to extract ‘k’ bits from a given position

Java 8Object Oriented ProgrammingProgramming

Extraction of k bits from the given position in a number involves converting the number into its binary representation. An example of this is given as follows −

Number = 20
Binary representation = 10100
k = 3
Position = 2
The bits extracted are 010 which represent 2.

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main (String[] args) {
      int number = 20, k = 3, pos = 2;
      int exNum = ((1 << k) - 1) & (number >> (pos - 1));
      System.out.println("Extract " + k + " bits from position " + pos + " in number " + number );
      System.out.println("The extracted number is " + exNum );
   }
}

Output

Extract 3 bits from position 2 in number 20
The extracted number is 2

Now let us understand the above program.

First, the values of number, k and position are defined. Then the required k bits are extracted from the given position in the number. Finally, the extracted number is displayed. The code snippet that demonstrates this is given as follows −

int number = 20, k = 3, pos = 2;
int exNum = ((1 << k) - 1) & (number >> (pos - 1));
System.out.println("Extract " + k + " bits from position " + pos + " in number " + number );
System.out.println("The extracted number is " + exNum );
raja
Published on 05-Dec-2018 17:05:21
Advertisements