Bit-Twiddling-Hacks-Collection icon indicating copy to clipboard operation
Bit-Twiddling-Hacks-Collection copied to clipboard

A single C header with many bitwise hacks

trafficstars

A single C header files containing functions with different bit twiddling hacks and a short explanation. I've put them together for myself as a cheatsheet and to play around with them. If you know any hacks not included, just submit a PR, or if you encounter any wrong stuff or a typo!

Short hack assortment:

  • Number multiplication, division
  • Even, odd and power checks
  • Uppercase, lowercase
  • Set, clear and flip bits
  • Insert and extract bitfields into words
  • Convert LSL, MSB, trailing bits
  • Masked copy
  • Bit swap
  • Population count
  • Bit island count
  • Bit scans
  • Lexiocographic permutations
  • Swapping without temporaries
  • Size comparison: min() and max() functions without branching
  • Modular additions
  • Power rounding
  • Significant masking
  • Logbase2 of power2 calculation using deBruijin sequence
  • Fast inverse sqrt
  • Bit reversion
  • Masked color operations
  • XOR en/decryption
  • Branchless assignments