Bitwise Operators and Binary Numbers Explained in Javascript

Binary Numbers from a Decimal Perspective

Decimal numbers have a base of 10, meaning that any decimal number can be represented as the sum of powers of 10.

This is a summation symbol. Think of it as a for loop, where ‘i’ is the counter, n is the exit condition, and x are each elements of a distinct array. Each pass, this sum would be added to a variable until we have a final result.
This might seem confusing. The upside-down ‘A’ means for all, the epsilon means in the set, the N is a natural number. Everything before the summation symbol is only adding constraints to all of the variables that they must be a positive integer (or zero). x_i are the digits of the number; b is the base; i is the current index; n is the last index.
Hexadecimal summation in decimal
Binary numbers are simple in that we only add one base of 2 or dont. Imagine this example like a reduce loop, where the array is [1,7] and i is the element, and each pass is added to the result.
Each digit represents the presence (1) or non-presence(0) of that power of 2.

Boolean Algebra

A bitwise operators &(AND), |(OR), ^(XOR), and ~(NOT) are operations used in boolean algebra. They are logical operators that compare variables that can only have two discrete values: true or false. I like to visualize them as functions:

These are logic gates. Don’t worry about their structure, just note the number of inputs and outputs.

Bitwise Operations

A Bitwise operation is just an operation that is performed bit by bit.

Bitwise Shift Operators

The operators ‘<<’ ‘>>’ and ‘>>>’ all work similar to an array shift/unshift. They push digits up or down the number. You must specify a number of digits to shift.

Why Use Bitwise Operators

A simple answer would be that you may not, in practice. Bitwise operations are incredibly efficient, but they make code harder to understand. For the same reason that we strive to create higher level programming languages, we tend to sacrifice small performance benefits for readability.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store