Java Power of 2 nextPowerOfTwo(int x)

Here you can find the source of nextPowerOfTwo(int x)

Description

Calculate the next power of 2, greater than or equal to x.

From Hacker's Delight, Chapter 3, Harry S.

License

Open Source License

Parameter

Parameter Description
x integer greater than 0

Return

next power of two

Declaration

private static int nextPowerOfTwo(int x) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2015 Oracle and/or its affiliates. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
 * which accompanies this distribution./*from  w w  w. java  2s .com*/
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *      Marcel Valovy - <marcelv3612@gmail.com>
 ******************************************************************************/

public class Main {
    /**
     * Calculate the next power of 2, greater than or equal to x.<p>
     * From Hacker's Delight, Chapter 3, Harry S. Warren Jr.
     *
     * @param x integer greater than 0
     * @return next power of two
     */
    private static int nextPowerOfTwo(int x) {
        assert x > 0;
        x |= --x >> 1;
        x |= x >> 2;
        x |= x >> 4;
        x |= x >> 8;
        x |= x >> 16;
        return x + 1;
    }
}

Related

  1. nextPowerOfTwo(int x)
  2. nextPowerOfTwo(int x)
  3. nextPowerOfTwo(int x)
  4. nextPowerOfTwo(int x)
  5. nextPowerOfTwo(int x)
  6. nextPowerOfTwo(int x)
  7. nextPowerOfTwo(int x)
  8. nextPowerOfTwo(int x)
  9. nextPowerOfTwoExact(int n)