Java Number Power powerOfTwo(final int i)

Here you can find the source of powerOfTwo(final int i)

Description

Returns a power of two, bigger or equal to the input.

License

Apache License

Declaration

public static int powerOfTwo(final int i) 

Method Source Code

//package com.java2s;
/*/*w ww.j a  va 2  s. c om*/
 * Copyright (C) 2013 Sebastien Diot.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    public static final int MIN_ARRAY_SIZE = 8;

    /** Returns a power of two, bigger or equal to the input. */
    public static int powerOfTwo(final int i) {
        // Don't create too small arrays
        if (i < MIN_ARRAY_SIZE) {
            return MIN_ARRAY_SIZE;
        }
        // If already power of two, then we are done
        if (2 * i == (i ^ (i - 1) + 1)) {
            return i;
        }
        // Not power of two, so "round up" by moving highest bit one notch up
        return 1 << (Integer.highestOneBit(i) + 1);
    }
}

Related

  1. powerOf10(int number)
  2. powerOf2Log2(int n)
  3. powerOf31(int n)
  4. powerOfN(Double v, int n)
  5. powerOfTen(int exp)
  6. powerOfTwo(int current, int desired)
  7. PowerOutageDistr()
  8. powerString(int power)
  9. powerString(int power)