您的位置:首页 > 其它

Integer.highestOneBit(int i)的作用

2016-03-09 19:58 393 查看

源码

/**
* 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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: