Integer BitCount RotateLeft Utilities

Use bitCount, rotateLeft, highestOneBit, and lowestOneBit for popcount, circular shifts, and power-of-two rounding without manual loops.

JavaCli Tooling

Code

snippet
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));
    }
}

How the snippet works

Integer BitCount RotateLeft Utilities keeps everything in the class BitSetMath and the function main.

Applying it

The demo output is labeled (bits set =, rotL 1 =, rotR 2 =), so every printed line maps back to its originating operation.

Statements that matter

int flags = 0b1011_0110;
int capacity = 100;

Interactive Tools for This Topic

FAQ

What does Integer BitCount RotateLeft Utilities print when run?
Execute the whole file; each printed line is prefixed with a label like `bits set =`, `rotL 1 =`, `rotR 2 =`.