Java floor floorPowerOf2(int n)

Here you can find the source of floorPowerOf2(int n)

Description

Computes the floor power of 2 within the range [1, 2^30].

License

Apache License

Parameter

Parameter Description
n The given argument.

Return

the floor power of 2.

Declaration

public static int floorPowerOf2(int n) 

Method Source Code

//package com.java2s;
/*/*  www.j av  a 2s  .c  o  m*/
 * Copyright 2015, Yahoo! Inc.
 * Licensed under the terms of the Apache License 2.0. See LICENSE file at the project root for terms.
 */

public class Main {
    private static final int IntTopPwrOf2 = 1 << 30;
    private static final int MaxIntShifts = 16;

    /**
     * Computes the floor power of 2 within the range [1, 2^30]. This is the largest positive power of
     * 2 that equal to or less than the given n. This algorithm finds the floor in a maximum of
     * lg(32)=5 iterations. <br>
     * For:
     * <ul>
     * <li>n &le; 1: returns 1</li>
     * <li>2^30 &le; n &le; 2^31 -1 : returns 2^30</li>
     * <li>n == a power of 2 : returns n</li>
     * <li>otherwise returns the largest power of 2 less than n</li>
     * </ul>
     * 
     * @param n The given argument.
     * @return the floor power of 2.
     */
    public static int floorPowerOf2(int n) {
        if (n <= 1) {
            return 1;
        }
        int f = ceilingPowerOf2(n);
        if (f <= n) {
            return f;
        }
        return f >> 1;
    }

    /**
     * Computes the ceiling power of 2 within the range [1, 2^30]. This is the smallest positive power
     * of 2 that equal to or greater than the given n. This algorithm finds the ceiling in a maximum
     * of lg(32)=5 iterations. <br>
     * For:
     * <ul>
     * <li>n &le; 1: returns 1</li>
     * <li>2^30 &le; n &le; 2^31 -1 : returns 2^30</li>
     * <li>n == a power of 2 : returns n</li>
     * <li>otherwise returns the smallest power of 2 greater than n</li>
     * </ul>
     * 
     * @param n The input argument.
     * @return the ceiling power of 2.
     */
    public static int ceilingPowerOf2(int n) {
        if (n <= 1) {
            return 1;
        }
        if (n >= IntTopPwrOf2) {
            return IntTopPwrOf2;
        }
        n--;
        for (int i = 1; i <= MaxIntShifts; i <<= 1) {
            int m = (n | (n >> i));
            if (n == m) {
                break;
            }
            n = m;
        }
        return ++n;
    }
}

Related

  1. floorPositive(float value)
  2. floorPot(float value)
  3. floorPOT(int n)
  4. floorPowerOf2(final int n)
  5. floorPowerOf2(final int x)
  6. floorPowerOfTwo(final int a)
  7. floorSec(long milli)
  8. floorSec(long valueMs)
  9. floorSqrt(long i)