Bitfoolish Operations in Javascript.
We all probably have never really had the need to do a single bitwise operation as developers, but some of the most important operations/functionalities used in programming use bitwise operations with the most popular (I think) being encryption.
Bitwise operations are, for the lack of a better word, intentional operations, carried out directly on the smallest representation of data that a computer can process…bits, using specific operators.
Bit, Byte, Bitten.
So while we deal with decimals (base 10s) on a day to day processing and interpretation of data, bitwise ops’ deal with binaries…0s and 1s and are of 7 types:
P.S. We will be using the bit representations of 4 and 5 in our examples which are 0100 and 0101 respectively.
- AND
Each bit is compared to the bits of the other using the & operator and 1 returned where both bits compared are 1.
0100 = 4 in base 10. So, 4 & 5 = 4.
2. OR
Each bit is compared using the | operator and 1 is returned where either of the bits compared have 1.
0101 = 5 in base 10. So, 4 | 5 = 5
3. XOR
Each bit is compared using the ^ operator and 1 is returned when either of the compared bits are 1 and not both.
0001 = 1 in base 10. So 4 ^ 5 = 1.
4. NOT
Inverts bits using the ~ operator.
~4 = ~0100 = 1011 = -5 (your eyes do not deceive you. All NOT operations yield -(a + 1) as their value)
5. LEFT SHIFT (shl)
Each bit is shifted to left by the designated amount and the tail appended with a 0 for each step using the << operator and the head is truncated.
4 << 1 === 0100 << 1 = 1000 = 8
5 << 2 === 0101 << 2 = 0001 0100 = 20
6. RIGHT SHIFT (shr)
Each bit is shifted right by the designated amount and the head appended with the same bit signature that was there before, using the >> operator. So if it was a 1 there, 1s keep getting added and versa.
4 >> 1 === 0100 >> 1 = 0010 = 2
7. ZERO FILL RIGHT SHIFT
Each bit is shifted right by the designated amount and the head appended with 0 irrespective of what the leftmost bit was using the >>> operator.
4 >>> 1 === 0100 >>> 1 = 0010 = 2.
Can this punishment please end?
Armed with some of these, we can do some pretty nice arithmetic with bitwise operations instead of our usual decimal maths.
Have a Javascript event and you’re looking for speakers, or you’re working on something awesome and need some tech assistance? Please…do reach out to me on twitter, @cozzbie