Compute modulus division by a power-of-2-number using Wrapper Class
Prerequisite : Compute modulus division by a power-of-2-number
Now as you know for getting n modulus 2k, we just need to return k bits(from LSB) in binary representation of n. In Java, you can use Wrapper class toBinaryString() method to get binary string representation of a number and getting substring from (str.length()-k) to end. And then by using Integer.parseInt(), you can convert this binary substring to number which is the remainder. Below is the Java program to demonstrate the same.
// Java program to Compute modulus // division by a power-of-2-number class Test { // Driver method public static void main(String[] args) { int num = 15 ; int two_power1 = 1 ; int two_power2 = 2 ; int two_power3 = 3 ; String binary = Integer.toBinaryString(num); int len = binary.length(); String rem1 = binary.substring(len-two_power1); String rem2 = binary.substring(len-two_power2); String rem3 = binary.substring(len-two_power3); int reme1 = Integer.parseInt(rem1, 2 ); int reme2 = Integer.parseInt(rem2, 2 ); int reme3 = Integer.parseInt(rem3, 2 ); System.out.println(num + "%" + "2^(" + two_power1 + ") = " + reme1); System.out.println(num + "%" + "2^(" + two_power2 + ") = " + reme2); System.out.println(num + "%" + "2^(" + two_power3 + ") = " + reme3); } } |
Output:
15%2^(1) = 1 15%2^(2) = 3 15%2^(3) = 7