Binary numbers in JavaScript
What is a binary number?
A binary number is a number expressed in the base-2 (binary) numeral system. An integer, (let’s say 5
, for example) is in decimal (base 10) form. But 5
can be converted to it’s binary (base 2) form. The binary form of 5
is 101
.
What’s the connection?
A binary number (like 101
) is a number that is written with 0
s and 1
s. Each 0
in a binary number represents 0
. Each 1
in a binary number represents 2^n
, where n
is the column position of that 1
. For example, the binary number 101
translates to 2^2 + 0 + 2^0
(4 + 0 + 1 = 5). The column position, n
, for the rightmost column is 0
. The column position, n
, for the second-to-last column is 1
. The column position, n
, for the third-to-last column is 2
and so on and so forth.
Let’s try another number. The binary form for the decimal number 7
is 111
. This translates to 2^2 + 2^1 + 2^0
(4 + 2 + 1 = 7).
One more. The binary form the decimal number 27
is 11011
. This translates to 2^4 + 2^3 + 0 + 2^1 + 2^0
(16 + 8 + 0 + 2 + 1 = 27).