Finds the integer x such that x=2q for some integer q, and x ? a. - Java java.lang

Java examples for java.lang:Math Function

Description

Finds the integer x such that x=2q for some integer q, and x ? 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 va 2  s . c o m
 * Contributors:
 *     Matthias-M. Christen, University of Basel, Switzerland - initial API and implementation
 ******************************************************************************/
//package com.java2s;

public class Main {
    /**
     * Finds the integer <var>x</var> such that
     * <var>x</var>=2<sup><var>q</var></sup> for some integer <var>q</var>, and
     * <var>x</var> &le; <var>a</var>.
     * 
     * @param a
     *            The value for which to find the power of 2 less or equal to
     *            <var>a</var>
     * @return A power of 2-integer less or equal to <var>a</var>
     */
    public static long getPrevPower2(final long a) {
        long v = a;
        v |= v >> 1;
        v |= v >> 2;
        v |= v >> 4;
        v |= v >> 8;
        v |= v >> 16;
        v |= v >> 32;

        return (v >> 1) + 1;
    }
}

Related Tutorials