DEV Community

Discussion on: Explain bitwise operator Like I'm Five

Collapse
 
lexlohr profile image
Alex Lohr

Computers are really stupid. They can only count to one. One would assume that this would make them useless, but they can do this very fast and a lot of times at once.

Counting in zeroes and one is called "binary". Binary numbers don't go "1, 2, 3, 4, 5" but instead, they go "1, 10, 11, 100, 101". The single digits in these numbers are called "bits". One can do math with these bits, but some math operations are faster than others on your computer: especially those who perform operations bit by bit without relying on other bits of the number, called "bitwise operations".

There are basically two kinds of bitwise operations: shifting and masking. Bit shifting allows you to multiply (shift left) or divide (shift right) by a multiple of 2 (2, 4, 8, 16, 32...), but results only in whole numbers. Bit masking allows you to switch single bits on and off, for example, if you need to know if a number is even or odd, you can just remove every bit but the one representing the "1" by using number & 1 and if it's set, you have an odd number. Or if you want to add 1 if the number is even, you could use number | 1.

Nowadays, computer and language compilers / interpreters are so fast that one rarely needs to use binary operations. The last time I used them in JavaScript was for centering a node during a mouse movement in IE6 (width >> 1 / height >> 1).

Collapse
 
drbearhands profile image
DrBearhands

IIRC you cannot assume what number primitives correspond to what bits nor that shifting corresponds to dividing and multiplying by 2. Big/little endian aside, the spec doesn't enforce it (in every language). That's one of the reasons we have boolean operators in the first place.

Collapse
 
lexlohr profile image
Alex Lohr

While this may not be the case in every language, at least JavaScript got you covered:

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used (see developer.mozilla.org/en-US/docs/W...).