Computes the binary logarithm of an integer. - Java java.lang

Java examples for java.lang:int Binary

Description

Computes the binary logarithm of an integer.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int n = 2;
        System.out.println(log2(n));
    }//from  w  w w .jav  a 2s  .  co  m

    /**
     * Computes the binary logarithm of an integer.
     *
     * @param n   Integer whose binary logarithm is to be computed.
     * @return   Logarithm of the integer with base 2.
     */
    public static int log2(int n) {

        if (n <= 0) {
            throw new IllegalArgumentException();
        }

        return 31 - Integer.numberOfLeadingZeros(n);
    }
}

Related Tutorials