Hey folks,
Back when I was learning in the pre-LLM era, I read a lot of articles (and books like Hacker’s Delight) filled with dozens of clever bitwise tricks. While they were fun and engaging (not really), I quickly realized that in everyday „JSON-moving“ jobs, most of them don’t really come up, especially when readability and maintainability matter more than squeezing out CPU cycles.
But, some of those tricks occasionally appear in performance-critical parts of public libraries I used or explored, or even in my code when the use case makes sense (like in tight loops). So instead of giving you a „Top 100 Must-Know Bitwise Hacks“ list, I’ve put together a short, practical one, focused on what I’ve found useful over the years:
- Multiplying and dividing by two using bit shifts (an arguable use case, but it gives an insight into how shifts affect the decimal value)
- Extracting parts of a binary value with shifts and masks
- Modulo with a power-of-two using masking
- Working with binary flags using bitwise AND, OR, and XOR
The examples are in C#, but the concepts easily apply across most languages.
If you just came across n & (m—1)
and thought, „What’s going on here?“ this might help.
submitted by /u/axel-user
[link] [comments]