In this tutorial, we will guide you how to show an integer’s 1s position on bit level.

Example:

26 => {1, 3, 4}

Use java.util.BitSet to store, well, a set of bits.

Util.java
package com.cloudberry.com.my;
import java.util.BitSet;

public class Util{
    public static BitSet fromInt(int num) {
        BitSet bs = new BitSet();
        for (int k = 0; k < Integer.SIZE; k++) {
            if (((num >> k) & 1) == 1) {
                bs.set(k);
            }
        }
        return bs;
    }

    public static int toInt(BitSet bs) {
        int num = 0;
        for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) {
             num |= (1 << k);
        }
        return num;
    }
}

The above utilities method in Util.java will be consumed in Main class.

Main.java
package com.cloudberry.com.my;

import static com.cloudberry.com.my.Util.fromInt;
import static com.cloudberry.com.my.Util.toInt;

import java.util.BitSet;
public class Main {
	public static void main(String args[]) {
		try {
			int num 		= 0b11010; //Which is 26 in decimal
			BitSet result 	= fromInt(num); 
			System.out.println("fromInt() is called => " + result); //Display which position from left to right, is flagged as 1s.
			System.out.println("toInt() is called => " +  toInt(result));
		}
		catch(IndexOutOfBoundsException ibex) {
			System.out.println(ibex.getMessage());
		}
	}
}
Output:
fromInt() is called => {1, 3, 4}
toInt() is called => 26

References

Static Import
BitSet

Last modified: May 24, 2018

Author