How to extract ‘k’ least significant bits from a number

Problem statement

Given n and k, extract the k least 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: 11

The binary representation of 11 is 1011, and we extract the 2 LSBs as 11.

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. Therefore, we return -1.

Solution

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

Code example

Let’s look at the code below:

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

Code explanation

  • Line 4: We define num.
  • Line 5: We define k.
  • Line 6: We convert num to binary form using the toBinaryString() method of the Integer class.
  • Lines 7 to 8: If the value of k is greater than the length of the binary string obtained in line 6, we print -1. Otherwise, we print the substring from the index of the difference of the length of the binary string and k to the end of the binary string.