Member-only story
Simple Bit Manipulation, pt. I
Bit Manipulation is a tool programmers use to flex that they have a CS degree. The concepts are rudimentary, but actually utilizing these low level functions is much harder. Great programmers like John Carmack and Terje Mathisen of Id Software can utilize bit manipulations for bespoke code, as they did with vector , but we’ll stick to known practices. While these operations work best in programming languages with a more intimate relationship with memory, such as C, I’ll be writing this code in JavaScript
Let’s start with the basic operators. In total, there are 6(ish):
& // AND
| // OR
^ // XOR
~ // NOT
<< // LEFT SHIFT
>> // RIGHT SHIFT
While going through these, it is important to remember that these lines of bits equal decimal numbers. So while switching 101 to 010 looks like a useless trick, we are actually converting 5 to 2
AND
Starting with an easy one, AND works as expected. This simply compares two bits and if they are both 1, returns 1
1&1 // returns 1
1&0 // returns 0
101 & 010 // returns 000
111 & 101 // returns 101
OR
Again, it says it right on the tin. This works in a similar, but distinctly not opposite way of AND. The operator will only return 1 if the either of bits being compared are 1.
0 | 0 // returns 0
1 | 0 // returns 1
101 | 010 // returns 111
111 | 000 // returns 111