获取一个正整数的最高位和更高一位值

一个正整数值采用Integer.highestOneBit(n)可以获取最高位,代码为:

public static int prevPowerOf2(int n) {
if (n <= 0)
throw new IllegalArgumentException();
return Integer.highestOneBit(n);
}

highestOneBit(int i)
{
i |= (i >>> 1);//右移过程使用零扩展
i |= (i >>> 2);
i |= (i >>> 4);
i |= (i >>> 8);
i |= (i >>> 16);
return i ^ (i >>> 1);
}
执行完i|=(i>>>1)后,最高位1的右边也成为1
执行i|=(i>>>2)后,最高位1右边的1+2=3位以内都成为1
执行i|=(i>>>4)后,最高位1右边的1+2+4=7位以内都成为1
......
执行i|=(i>>>16)后,最高位1右边的1+2+4+8+16=31位以内都成为1
i^(i>>>1)即可将最高位1右边的1都置为0


public static int nextPowerOf2(int n) {
if (n <= 0 || n > (1 << 30))
throw new IllegalArgumentException();
n -= 1;
n |= n >> 16;
n |= n >> 8;
n |= n >> 4;
n |= n >> 2;
n |= n >> 1;
return n + 1;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值