Binary numbers are numbers which are expressed in base 2 notation, rather than the base 10 we are used to. Consider how we normally count in base 10 - when we reach 10, we have to add an extra number to express it. Similarly, in base 2, when we reach 1, the next number has to be expressed by adding a new number to it. So while 1 is equivalent to 1, 10 is equivalent to 2.
You can convert any binary numbers to decimal using the calculator below.
You've probably used
parseInt? If you use the second argument of
parseInt, you can set the base:
let x = parseInt('10101', 2); console.log(x); // Returns 21
Most likely, you'll want to use base 2, but you can use any base you like here. So
parseInt('10010', 3) will convert a base 3 number to a decimal too. This is a pretty useful and little used
As mentioned previously, you can calculate a binary value in decimal when you consider that you can only ever go as high as
1 in binary, just as you can only ever go as high as
9 in decimal. So as in decimal, when you reach
9, you have to add another number to represent
10, in binary, when you reach
1, you have to add another number to represent
2 - so
The easiest way to convert a binary number to a decimal is to understand that each number in a binary can be represented like so:
BINARY: 1 0 1 0 1 0 1 DECIMAL: 64 32 16 8 4 2 1
All we have to do to convert a binary number to a decimal, is to know that each number can be represented in binary as a decimal number which increases by a multiple of 2 each time. So the last number, is
1, and then the next is
2, and the next is
4, and so on.
To convert a binary like
1010101 to decimal, we multiply each number by its decimal representation. So we can do:
1 * 1- giving us 1
0 * 2- giving us 0
1 * 4- giving us 4
0 * 8- giving us 0
1 * 16- giving us 16
0 * 32- giving us 0
1 * 64- giving us 64
Then we add them all up! So
64 - giving us 85!