
Handy Bit Manipulation Tricks
I was digging through React's source code and stumbled upon some bitmask logic for handling component states. At first glance, it looked cryptic—just a bunch of & , | , and << operators. But once I understood what was happening, it clicked. These operations are ridiculously fast and efficient. Here are some tricks I find myself reaching for when performance actually matters. Basic Bit Operations Setting a Bit To set the bit at position pos , use the bitwise OR operator. Think of (1 << pos) as a laser pointer—you're pointing it exactly at one spot, and | is the "turn on" switch: function setBit ( n : number , pos : number ): number { return n | ( 1 << pos ); } Example: Setting bit at position 2 in 0b1010 gives us 0b1110 0b1010 | 0b0100 ( laser pointer at position 2 ) ----------- 0b1110 Clearing a Bit To clear a bit at position pos , we AND with the inverted mask: function clearBit ( n : number , pos : number ): number { return n & ~ ( 1 << pos ); } Example: Clearing bit at position 1 in
Continue reading on Dev.to JavaScript
Opens in a new tab



