Computes log2 (ceil (a)). - Java java.lang

Java examples for java.lang:Math Calculation

Description

Computes log2 (ceil (a)).

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 Matthias-M. Christen, University of Basel, Switzerland.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * // w  w  w . j a  v a 2  s  .  co m
 * Contributors:
 *     Matthias-M. Christen, University of Basel, Switzerland - initial API and implementation
 ******************************************************************************/
//package com.java2s;

public class Main {
    /**
     * Computes log2 (ceil (<code>a</code>)).
     * @param a
     * @return
     */
    public static long log2(final long a) {
        if (a <= 0)
            throw new RuntimeException(
                    "The argument must be strictly positive");

        /*
        int j = -1;
        for (int i = a; i > 0; i >>= 1)
           j++;
        return j;
         */

        long v = a;
        final long b[] = new long[] { 0x00000002, 0x0000000c, 0x000000f0L,
                0x0000ff00L, 0xffff0000L, 0xffffffff00000000L };
        long r = 0;
        int s = 32;

        for (int i = 5; i >= 0; i--) {
            if ((v & b[i]) != 0) {
                v >>= s;
                r |= s;
            }
            s >>= 1;
        }

        return r;
    }
}

Related Tutorials