Convert number bases by hand in JavaScript
Advanced · 5 min read
JavaScript can already turn a number into another base with toString(radix) and read it back with parseInt(text, radix). So why do it by hand? Because writing the conversion yourself shows you how bases work, and because the built-in round trip has gaps: parseInt ignores fractions, and very long base-36 codes come back as the wrong number without any error.
In this tutorial you will write toBase using repeated division, check it against toString, write fromBase that also reads the part after the point, and then find the two places where the round trip quietly goes wrong. You need to know loops, % (the remainder) and Math.floor.
Repeated division, by hand
To write 255 in base 16, keep dividing by 16 and note the remainders:
- 255 ÷ 16 = 15, remainder 15 (the digit
f). - 15 ÷ 16 = 0, remainder 15 (another
f). - The number is now 0, so stop.
The remainders are the digits, but they come out backwards: the first remainder is the last digit (the ones place). Here both are f, so 255 is ff. Try 10 in base 2: the remainders are 0, 1, 0, 1, and reading them backwards gives 1010.
Digits past 9
Bases above 10 need more digit characters. A string of all 36 makes the lookup easy: the character at position 10 is a, at 15 is f, and at 35 is z.
const DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz';
console.log(DIGITS[15], DIGITS[35]); // f z
Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.
66 Reading a base back, and where the round trip loses
hardConvert to a base by hand with repeated division, and check it against toString. Read it back with parseInt and a radix. Then find a base-36 string that parseInt cannot represent, and one that parseInt only half reads.
Stuck? Three hints, smallest first
- 1. Repeated division: the remainders are the digits, produced least significant first.
- 2.
parseIntstops at the first character that is not a digit in that base — including the point. - 3. Any result past
Number.MAX_SAFE_INTEGERis a nearest-double, so the round trip cannot be exact.
Step 1: toBase with repeated division
function toBase(n, b) {
if (n === 0) return '0';
let rest = n;
let out = '';
while (rest > 0) {
out = DIGITS[rest % b] + out; // remainders come out backwards
rest = Math.floor(rest / b);
}
return out;
}
console.log(toBase(255, 16), toBase(10, 2)); // ff 1010
rest % b is the next digit. Adding it to the front of out fixes the backwards order. Math.floor(rest / b) drops what we just used. Zero needs its own line, because the loop would not run at all and would return an empty string.
Step 2: check it against toString
One example is not proof. Test many values in several bases and compare each with the built-in:
const values = [0, 1, 7, 255, 4095, 99999];
const bases = [2, 3, 8, 16, 36];
const agrees = values.every((n) => bases.every((b) => toBase(n, b) === n.toString(b)));
console.log(agrees); // true
const roundTrips = values.every((n) => bases.every((b) => parseInt(n.toString(b), b) === n));
console.log(roundTrips); // true
every is true only if the test passes for every item. Nesting two every calls checks all 30 pairs of value and base. The second line checks that parseInt with the same radix reads each string back to the original number.
Step 3: parseInt stops at the point
In binary, places after the point are worth 1/2, 1/4, 1/8 and so on. So 1010.11 is 8 + 2 + 1/2 + 1/4 = 10.75. Watch what parseInt does with it:
console.log(parseInt('1010.11', 2)); // 10
parseInt reads digits until it meets a character it can't use, then stops. The point is such a character, so it returns 10 and drops .11 without telling you. There is no parseFloat with a radix to help.
Step 4: fromBase reads the fraction too
Split the string at the point. Let parseInt read the whole part, then loop over the fraction digits, giving each one a place value of 1/b, then 1/b², and so on:
function fromBase(s, b) {
const [whole, frac = ''] = s.split('.');
let value = parseInt(whole, b);
let scale = 1 / b;
for (const ch of frac) {
value += parseInt(ch, b) * scale;
scale /= b;
}
return value;
}
console.log(fromBase('1010.11', 2)); // 10.75
console.log(fromBase((0.1).toString(2), 2) === 0.1); // true
frac = '' is a default: if there is no point, there is no fraction to loop over. The second line takes the long binary form of 0.1 and reads it back. It comes back exactly equal to 0.1, because in base 2 every step (halving scale, adding a digit) is exact for a number stored in binary.
Step 5: long base-36 codes
JavaScript numbers count whole numbers exactly only up to Number.MAX_SAFE_INTEGER, which is 9007199254740991. Past that, the gaps between storable numbers are bigger than 1.
const tenZ = parseInt('zzzzzzzzzz', 36);
console.log(tenZ, Number.isSafeInteger(tenZ)); // 3656158440062975 true
const twelveZ = parseInt('zzzzzzzzzzzz', 36);
console.log(twelveZ, Number.isSafeInteger(twelveZ)); // 4738381338321617000 false
Ten z's fits, and is exact. Twelve z's should be 4738381338321616895, which is 36¹² - 1, but that is past the safe limit. parseInt returns the nearest number it can store, which is 4738381338321616896: 1 too large. (console.log prints it as 4738381338321617000, because it only shows as many digits as it needs to tell numbers apart.) BigInt can do the exact sum and show the gap:
const overshoot = Number(BigInt(twelveZ) - (36n ** 12n - 1n));
console.log(overshoot); // 1
There is no error and no NaN. If that code was an ID in a link, you would quietly look up the wrong record. For long codes, read digit by digit into a BigInt instead.
Step 6: prefixes are not digits
console.log(parseInt('0b1010', 2)); // 0
console.log(Number('0b1010')); // 10
parseInt reads the 0, sees b, which is not a binary digit, and stops. Number understands the 0b prefix and gives 10. Strip prefixes before calling parseInt.
The full solution
The answer panel has DIGITS, toBase and fromBase, and prints the comparison with toString, the round trip check, 1010.11 both ways, 0.1 through base 2, the ten and twelve z cases with the overshoot, and the 0b prefix. Press Run to see the output.
const DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz';
function toBase(n, b) {
if (n === 0) return '0';
let rest = n;
let out = '';
while (rest > 0) {
out = DIGITS[rest % b] + out; // remainders come out backwards
rest = Math.floor(rest / b);
}
return out;
}
// parseInt stops at the point, so a fractional part needs its own loop.
function fromBase(s, b) {
const [whole, frac = ''] = s.split('.');
let value = parseInt(whole, b);
let scale = 1 / b;
for (const ch of frac) {
value += parseInt(ch, b) * scale;
scale /= b;
}
return value;
}
const values = [0, 1, 7, 255, 4095, 99999];
const bases = [2, 3, 8, 16, 36];
const agrees = values.every((n) => bases.every((b) => toBase(n, b) === n.toString(b)));
const roundTrips = values.every((n) => bases.every((b) => parseInt(n.toString(b), b) === n));
const tenZ = parseInt('zzzzzzzzzz', 36);
const twelveZ = parseInt('zzzzzzzzzzzz', 36);
const overshoot = Number(BigInt(twelveZ) - (36n ** 12n - 1n));
console.log('by hand vs toString:', toBase(255, 16), (255).toString(16), agrees);
console.log('round trip :', roundTrips);
console.log('parseInt at a point:', parseInt('1010.11', 2), 'but fromBase gives', fromBase('1010.11', 2));
console.log('0.1 through base 2 :', fromBase((0.1).toString(2), 2));
console.log('ten z in base 36 :', tenZ, Number.isSafeInteger(tenZ));
console.log('twelve z :', twelveZ, 'true value 4738381338321616895');
console.log('overshoot :', overshoot);
console.log('0b prefix :', parseInt('0b1010', 2), 'but Number gives', Number('0b1010'));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('repeated division agrees with toString across six values and five bases', agrees, true);
test('and parseInt with a radix reads every one of them back', roundTrips, true);
test('parseInt stops at the point, reading 1010 and dropping .11', parseInt('1010.11', 2), 10);
test('a fraction loop picks up the rest: 1010.11 is 10.75', fromBase('1010.11', 2), 10.75);
test('and 0.1 survives a trip through base 2 exactly', fromBase((0.1).toString(2), 2) === 0.1, true);
test('ten z in base 36 is 3656158440062975, still a safe integer', [tenZ, Number.isSafeInteger(tenZ)], [3656158440062975, true]);
test('twelve z is not, and comes back 1 too large', [Number.isSafeInteger(twelveZ), overshoot], [false, 1]);
test('parseInt does not know 0b, so it reads the 0 and stops', parseInt('0b1010', 2), 0);
test('while Number understands the prefix and gives 10', Number('0b1010'), 10);
The two directions are not symmetrical. toString(radix) handles fractions and signs; parseInt reads an integer and stops at the first character it cannot use, which includes the decimal point — so parseInt('1010.11', 2) is 10, silently. There is no parseFloat with a radix, so a fractional base needs the digit loop above, and the loop is exact in base 2 because a double already is a binary fraction: 0.1 round-trips to itself, bit for bit.
The base-36 case is the honest limit. Ten z's is 3656158440062975, inside Number.MAX_SAFE_INTEGER, and it round-trips. Twelve z's is 4738381338321616895, past it, and parseInt returns the nearest double — exactly 1 too large. No error, no NaN: an identifier read back from a short URL code would simply be the wrong identifier. Parse long base-36 strings digit by digit into a BigInt.
Common mistakes
- Reading the remainders in the order they come out. They are backwards. Add each new digit to the front of the string.
- Trusting
parseIntwith a fraction. It stops at the point and returns only the whole part. - Using numbers for long base-36 IDs. Past
Number.MAX_SAFE_INTEGERthe result is rounded. Use BigInt.
Try it yourself
- Use
toBaseto write 2024 in base 2, base 8 and base 36, and check each withtoString. - Make
toBasehandle negative numbers by converting-nand putting a minus sign in front. - Write
fromBase36Big(s)that loops over the characters and builds a BigInt withvalue = value * 36n + BigInt(digit). Check it on twelve z's.