Related Tags

bitwise

# Extract ‘k’ most significant bits from a number

Ravi

### Problem Statement

Given n and k, extract the k most significant bits of n. Return -1 if k is larger than the number of bits used to represent n.

Example 1

• Input: n=11, k=2
• Output: 10

The binary representation of 11 is 1011, and we extract the 2 MSBs i.e. 10.

Example 2

• Input: n=14, k=5
• Output: -1

The binary representation of 14 is 1110. Only 4 bits are used in the binary representation of 14, and the ask is for 5. Hence, we return -1.

### Solution

1. Convert the decimal value to binary form.
2. Take the first k characters from the result of step 1

### Code

public class Main{

public static void main(String[] args) {
int num=11;
int k=2;
String binaryForm = Integer.toBinaryString(num);
if(k > binaryForm.length()) System.out.println("-1");
else System.out.println(binaryForm.substring(0, k));
}
}

### Explanation

• Line 4: num is defined.
• Line 5: k is defined.
• Line 6: num is converted to binary form.
• Lines 7-8: If the value of k is greater than the length of the binary string obtained in line 6, we print -1. Otherwise, the substring from 0 to the index of the difference of the length of the binary string and k is printed.

RELATED TAGS

bitwise

CONTRIBUTOR

Ravi
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time