Integer.highestOneBit(int i)的作用

源码

    /**
     * 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。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值