How it works
At its core, every number system operates on a concept called positional notation. The value of a digit depends not just on the digit itself, but on its position relative to the radix (decimal) point.
The General Base Formula
To convert a number from any arbitrary base (b) into our standard Decimal (base-10) system, we use polynomial expansion. For a number consisting of digits d, the decimal value N is calculated as:
N=i=−m∑ndi⋅bi
Where:
- b is the starting base (e.g., 16 for hex, 2 for binary).
- di is the value of the digit at position i.
- n is the highest positional index (left of the decimal).
- −m is the lowest positional index (right of the decimal).
Example: Binary to Decimal
Let's convert the binary number 1011.01 to decimal:
- Map the integer part (
1011):
(1×23)+(0×22)+(1×21)+(1×20)=8+0+2+1=11
- Map the fractional part (
.01):
(0×2−1)+(1×2−2)=0+0.25=0.25
- Combine them: 11.25
Converting Decimal to Other Bases
To move from decimal to another base (like Hexadecimal), the algorithm handles the integer and fractional parts separately:
- The Integer Part (Repeated Division): You divide the decimal number by the target base. The remainder becomes the next digit (starting from the least significant digit). You repeat this with the quotient until the quotient is zero.
- The Fractional Part (Repeated Multiplication): You multiply the fractional part by the target base. The integer portion of the result becomes the next digit in the fraction. You strip the integer and repeat with the new fraction until you reach zero or your desired precision limit.
The integer portion uses BigInt. Fractional portions use JavaScript floating-point numbers and are limited to 10 output digits, so a repeating or very long fraction may be rounded or truncated.