Bit Twiddling Hacks Summary
Bit Twiddling Hacks Summary This note summarizes practical techniques from Bit Twiddling Hacks. It follows the same style as common-algorithm-patterns.md: each topic has Explanation + C++ Framework. 0) Preconditions and Portability Explanation Bit hacks are highly sensitive to integer representation and shift semantics: Prefer unsigned fixed-width types like uint32_t / uint64_t. Right-shifting negative signed values is implementation-defined. Be careful with overflow-prone expressions such as x - y. Code Framework 1 2 3 4 5 6 7 #include <bit> #include <cstdint> #include <limits> using u32 = uint32_t; using u64 = uint64_t; using i32 = int32_t; 1) Sign and Opposite-Sign Detection Explanation Sign extraction is often normalized to -1 / 0 / 1. Two values have opposite signs when their sign bits differ. Code Framework 1 2 3 4 5 6 7 int sign3(int x) { return (x > 0) - (x < 0); // -1 / 0 / 1 } bool oppositeSigns(int x, int y) { return (x ^ y) < 0; } 2) Branchless abs / min / max Explanation Useful when branch misprediction is expensive, but always benchmark against normal standard-library versions first. ...