 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to extract ‘k’ bits from a given position
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
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 );Advertisements
 