Integer BitCount RotateLeft Utilities
Use bitCount, rotateLeft, highestOneBit, and lowestOneBit for popcount, circular shifts, and power-of-two rounding without manual loops.
Code
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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.