Open In App
Related Articles

Compute modulus division by a power-of-2-number using Wrapper Class

Improve Article
Save Article
Like Article

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);


15%2^(1) = 1
15%2^(2) = 3
15%2^(3) = 7

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Jun, 2017
Like Article
Save Article
Similar Reads
Complete Tutorials