源码
/**
* Returns an {@code int} value with at most a single one-bit, in the
* position of the highest-order ("leftmost") one-bit in the specified
* {@code int} value. Returns zero if the specified value has no
* one-bits in its two's complement binary representation, that is, if it
* is equal to zero.
*
* @return an {@code int} value with a single one-bit, in the position
* of the highest-order one-bit in the specified value, or zero if
* the specified value is itself equal to zero.
* @since 1.5
*/
public static int highestOneBit(int i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
JDK的解析
返回具有至多单个 1 位的 int 值,在指定的 int 值中最高位(最左边)的 1 位的位置。如果指定的值在其二进制补码表示形式中不具有 1 位,即它等于零,则返回零。
简单的说法
- 如果一个数是0, 则返回0;
- 如果是负数, 则返回 -2147483648:【1000,0000,0000,0000,0000,0000,0000,0000】(二进制表示的数);
- 如果是正数, 返回的则是跟它最靠近的比它小的2的N次方
比如 17:
二进制是【0000,0000,0000,0000,0000,0000,0001,0001】
highestOneBit(17)返回的是最高位的1个1, 其它全是0 的二进制数:【0000,0000,0000,0000,0000,0000,0001,0000】,其实就是16。
本文详细解析了Java JDK中的highestOneBit方法,该方法能够找到一个整数中最高位1的位置,并返回对应的2的幂次方值。对于数值0和负数也有特别说明。
2210

被折叠的 条评论
为什么被折叠?



