private static int closestPowerOfTwo ( int value ) { int n = value - 1 ; n |= n >>> 1 ; n |= n >>> 2 ; n |= n >>> 4 ; n |= n >>> 8 ; n |= n >>> 16 ; return ( n < 0 ) ? 1 : ( n >= ( 1 << 30 ) ) ? 1 << 30 : n + 1 ; }
Finds closest power of two for given integer value . Idea is simple duplicate the most significant bit to the lowest bits for the smallest number of iterations possible and then increment result value by 1 .