Search code examples
javabit-manipulation

Get index of least significant set bit for a long in Java


I found some code here that does what I am looking for for an int but when I plug in a long and the LSB is the 64th bit, it returns 0 instead of 64. I could do an explicit check for that case but there must be a better way.

public class Test{
    public static void main(String[] args){
        long test = 0b1000000000000000000000000000000000000000000000000000000000000000L;
        
        //this should print "64"
        System.out.println(getLSBIndx(test));
    }
    public static int getLSBIndx(long n){
        if(n == 0) return -1;
        return (int)((Math.log10(n & -n)) / Math.log10(2)) ;
    }
}

Solution

  • You can calculate it based on Long.numberOfTrailingZeros.

    public static int getLSBIndx(long n) {
        return n == 0 ? -1 : Long.numberOfTrailingZeros(n) + 1;
    }