Decimal to Binary
For instance, we have number 7
, which is base-10 number. Then, we need to convert to base-2 (binary) system.
The base-2 system uses the addition of power of 2's to get the number we have in another radix system.
So to get the value from the other base system (base-10 for example), we continuously divide that number with 2, and take the remainder of each division.
In paper and pen scribbling, we do this:
7 ÷ 2 ➡️ closest multiplier is 3, remainder 1
3 ÷ 2 ➡️ closest multiplier is 1, remainder 1
1 ÷ 2 ➡️ the only multiplier is 0, remainder 1
Put all remainders as a number.
Take each from the BOTTOM: 1 ➡️ 1 ➡️ 1.
Meaning 7 in binary system is 111.
$7_10 = 111_2$
Or, we could use the addition method of power of 2:
$$ 7 = (\bo1 × 2^2) + (\bo1 × 2^1) + (\bo1 × 2^0)$$
Look at the multiplier (1), read it from the LEFT: 1 ➡️ 1 ➡️ 1.
Similar to prior method, 7 in base-10 is equal to 111 in base-2 system.
$7_10 = 111_2$
JavaScript: Decimal to Binary
Use:
toString(2)
The output will be String
type.
Example:
To convert the output to number, use Number()
. Like so:
This method also works for negative number.
For floating number (number with decimal point), this method will also work (but with some limitation for the radix point, the approximation).
Example:
JavaScript: One Base to Another Base
We use toString()
to convert one base to another:
BUT, that only works for decimal input. For other base input, we need one preliminary step to convert it to its actual base, then we can convert it to another base.
It's using parseInt(input, radix)
function.
The radix
value ranges from 2 (base-2) to 36 (base-36).
For instance, converting base-16 (hexadecimal) 21 to decimal:
So then ➡️ 2116 = 3310
Converting base-2 (binary) 11011 to base-8 (octal):
➡️ 110112 = 338
Converting base-12 (dozenal) 322 to base-5 (pental):
➡️ 32212 = 33135
JavaScript: Conversion Error
If the input cannot be converted, usually because of the input error, the output will produce NaN
.
If the error because of the unsupported radix
value in toString
, the browser will throw RangeError
exception.
JavaScript: Base Conversion Formula
We could also put preceding filter before parseInt
to make sure the input is valid, or in between parseInt
and toString()
or something else.
Let's create a function named radixConverter
.
This function has 3 arguments: input
, fromBase
, and toBase
.
To learn more about the base-10 to base-2 conversion (and vice versa) there's this explanation
Oh wait, there's an application which can accommodate until base-62.
Comments
Post a Comment