方法定义
public static int highestOneBit(int i)
- 功能:返回给定整数二进制表示中最高位(最左侧)的1所对应的值
- 返回值:仅保留最高位1的整数(其他位均为0)
- 特殊值:
- 输入
0
返回 0
- 输入负数返回
-2147483648
(0x80000000
)
功能原理
- 核心操作:通过位运算提取最高位的1
- 位运算步骤:
i |= (i >> 1); // 最高位1向右扩散1位
i |= (i >> 2); // 扩散2位
i |= (i >> 4); // 扩散4位
i |= (i >> 8); // 扩散8位
i |= (i >> 16); // 扩散16位
return i - (i >>> 1); // 保留最高位1
- 效果:将最高位1右侧所有位变为1,然后通过减法保留最高位
示例代码
// 正数测试
System.out.println(Integer.highestOneBit(10)); // 8 (二进制 1000)
System.out.println(Integer.highestOneBit(255)); // 128 (10000000)
System.out.println(Integer.highestOneBit(1023)); // 512 (1000000000)
// 特殊值
System.out.println(Integer.highestOneBit(0)); // 0
System.out.println(Integer.highestOneBit(1)); // 1
System.out.println(Integer.highestOneBit(-1)); // -2147483648
System.out.println(Integer.highestOneBit(Integer.MAX_VALUE)); // 1073741824
使用场景
- 计算最接近的2的幂:
int nextPowerOfTwo(int num) {
int highBit = Integer.highestOneBit(num);
return (highBit == num) ? highBit : highBit << 1;
}
- 位掩码生成:
// 生成最高位掩码:0x80000000
int highestBitMask = Integer.highestOneBit(-1);
- 数据结构优化(如HashMap容量计算):
// 计算不小于cap的最小2的幂
int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : n + 1;
}
关键特性
输入类型 |
返回值 |
二进制表示 |
正数 |
≤ 输入的最大2的幂 |
000...100...0 |
0 |
0 |
000...000 |
负数 |
-2147483648 (0x80000000 ) |
1000000000000000 |
Integer.MAX_VALUE |
1073741824 |
0100000000000000 |
常见错误
- 误解负数结果:
// 错误预期:认为负数会返回正数结果
int result = Integer.highestOneBit(-10); // 实际返回-2147483648
- 忽略0的特殊性:
// 未处理0导致逻辑错误
if (Integer.highestOneBit(flags) > 0) { // 当flags=0时跳过
- 混淆最高位与最低位:
// 错误:使用lowestOneBit替代
int wrong = Integer.lowestOneBit(10); // 返回2 (00000010)
最佳实践
- 正数范围检查:
public static int safeHighestBit(int num) {
if (num <= 0) return 0;
return Integer.highestOneBit(num);
}
- 位运算替代方案(无分支优化):
// 直接位操作(等效实现)
public static int customHighestOneBit(int i) {
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i & ~(i >>> 1);
}
- 性能关键场景优化:
| 场景 | 推荐方案 | 时钟周期 |
|-----------------------|--------------------------------|------------|
| 单次计算 |
Integer.highestOneBit()
| ~3 cycles |
| 循环计算(已知正数) | 内联位运算 | ~1 cycle |
| 需要2的幂边界 | Integer.bitCount()
组合 | 略高 |
性能分析
总结
关键点 |
说明 |
核心功能 |
提取整数最高位1对应的值 |
正数行为 |
返回≤输入的最大2的幂 |
负数行为 |
固定返回-2147483648 |
零值处理 |
返回0 |
主要用途 |
位运算优化、数据结构容量计算 |
性能等级 |
⚡️ 极快(JVM intrinsic优化) |
替代方案 |
手动位运算(性能敏感场景) |