实现说明
底层就是类 BitSetMath和函数 main。
使用要点
- 演示输出是带标签的(
bits set =、rotL 1 =、rotR 2 =),每个操作都会留下自己的一行标注。
常见问题
运行「Integer 位工具函数」会打印什么?
整个文件跑完,输出行以 bits set =、rotL 1 =、rotR 2 = 这类前缀开头。
核心语句
int flags = 0b1011_0110;
int capacity = 100;
代码示例
public class BitSetMath {
public static void main(String[] args) {
// 这些静态方法就是 Integer 自带的 bit utilities
int flags = 0b1011_0110;
// bitCount:1 的个数(汉明重量)
System.out.println("bits set = " + Integer.bitCount(flags));
// rotateLeft/rotateRight:32 位循环移位,丢的位从另一侧回来
System.out.println("rotL 1 = " + Integer.toBinaryString(Integer.rotateLeft(flags, 1)));
System.out.println("rotR 2 = " + Integer.toBinaryString(Integer.rotateRight(flags, 2)));
// highestOneBit:只留最高位的 1,用来向下取整到 2 的幂
System.out.println("highest one bit = " + Integer.highestOneBit(100));
// lowestOneBit:隔离最低位的 1
System.out.println("lowest = " + Integer.toBinaryString(Integer.lowestOneBit(flags)));
// 惯用法:100 取整到下一个 2 的幂 128
int capacity = 100;
System.out.println("next power of two = " + (Integer.highestOneBit(capacity - 1) << 1));
}
}