- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 );
- Related Articles
- Python program to extract ‘k’ bits from a given position?
- Java program to reverse an array upto a given position
- Python program to extract characters in given range from a string list
- Search for a character from a given position in Java
- Java Program to shift bits in a BigInteger
- C program to rotate the bits for a given number
- Python – Extract element from a list succeeded by K
- Java Program to reverse a given String with preserving the position of space.
- Python – Extract Rear K digits from Numbers
- Golang Program to extract the last two digits from the given year
- Haskell Program to extract the last two digits from the given year
- Java program to count total bits in a number
- Python program to extract Keywords from a list
- How to extract substring from a sting starting at a particular position in MySQL?
- Java program to reverse bits of a positive integer number

Advertisements