工具类
Util工具类提供计算容量2的n次方的方法
/**
* 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 Value to round up
* @return The next power of 2 from x inclusive
*/
public static int ceilingNextPowerOfTwo(final int x)
{
return 1 << (32 - Integer.numberOfLeadingZeros(x - 1));
}
顺便学习一下Integer有趣的函数:
numberOfLeadingZeros
public static int numberOfLeadingZeros(int i)
Returns the numberof zero bits preceding the highest-order ("leftmost") one-bit in thetwo's complement binary representation of the specified int value. Returns 32 if the specified value has no one-bits in its two'scomplement representation, in other words if it is equal to zero.
Note that this method is closely related to the logarithmbase 2. For all positive int values x:
· floor(log2(x))= 31 -numberOfLeadingZeros(x)
· ceil(log2(x))= 32 -numberOfLeadingZeros(x - 1)
Returns:
the number of zerobits preceding the highest-order ("leftmost") one-bit in the two'scomplement binary representation of the specified int value, or 32 ifthe value is equal to zero.
Since:
1.5
numberOfTrailingZeros
public static int numberOfTrailingZeros(int i)
Returns the numberof zero bits following the lowest-order ("rightmost") one-bit in thetwo's complement binary representation of the specified int value. Returns 32 if the specified value has no one-bits in its two'scomplement representation, in other words if it is equal to zero.
Returns:
the number of zerobits following the lowest-order ("rightmost") one-bit in the two'scomplement binary representation of the specified int value, or 32 if thevalue is equal to zero.
Since:
1.5
bitCount
public static int bitCount(int i)
Returns the numberof one-bits in the two's complement binary representation of the specified int value. This function is sometimes referred to as thepopulation count.
Returns:
the number ofone-bits in the two's complement binary representation of the specified int value.
Since:
1.5