Round-trip number bases with parseInt in JavaScript
Intermediate · 4 min read
Color codes like #ff8800, file permissions like 755, short ids like 3x7k: these are all numbers written in a different base. JavaScript can write a number in any base from 2 to 36 and read it back again. The writing side is strict. The reading side, parseInt, is surprisingly loose.
In this tutorial you will print 255 in hex, binary, octal and base 36, read each one back, and find out exactly what parseInt does when it only partly understands a string. You will also see what a negative number looks like in hex and what happens if you ask for a base that doesn't exist. You need to know what a function call and a string are.
What a base is
We normally count in base 10: ten digits, 0 to 9, and each place is worth ten times the one to its right. Other bases work the same way with a different number of digits:
- Base 2 (binary) uses 0 and 1.
11111111is 255. - Base 8 (octal) uses 0 to 7.
377is 255. - Base 16 (hex) uses 0 to 9, then a to f for 10 to 15.
ffis 15 * 16 + 15 = 255. - Base 36 uses 0 to 9 and all 26 letters.
73is 7 * 36 + 3 = 255.
The base is also called the radix.
The two tools
number.toString(radix)writes a number as text in that base.parseInt(text, radix)reads text in that base and gives back a number.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
84 Bases, both directions
fairPrint 255 in hex, binary, octal and base 36, then read those strings back with parseInt. Find out what parseInt does with a string it only partly understands, what (-255).toString(16) looks like, and what happens if you ask for base 1.
Stuck? Three hints, smallest first
- 1.
Number.prototype.toStringtakes an optional radix from 2 to 36. - 2.
parseInttakes the radix as its second argument, and reads as far as it can. - 3.
parseInt('1e3')andNumber('1e3')do not agree.
Step 1: write 255 in four bases
console.log((255).toString(16), (255).toString(2), (255).toString(8), (255).toString(36)); // ff 11111111 377 73
The brackets around 255 are needed. Without them, JavaScript reads 255. as the start of a decimal number and the line is a syntax error.
Step 2: negative numbers
console.log((-255).toString(16)); // -ff
You might expect the bit pattern that computers use inside, but toString keeps it simple: a minus sign in front of the positive digits.
Step 3: read them back, with the radix
console.log(parseInt('ff', 16), parseInt('0xff', 16)); // 255 255
console.log(parseInt('ff')); // NaN
console.log(parseInt('0xff')); // 255
With 16 as the second argument, ff reads as 255. Leave the radix out and parseInt assumes base 10, where f is not a digit, so you get NaN. The one exception is a 0x prefix: with no radix, parseInt reads it as hex. Always pass the radix, so nobody has to remember these rules.
Step 4: strings it only partly understands
This is where parseInt surprises people.
console.log(parseInt('102', 2)); // 2
console.log(parseInt('12abc', 16)); // 76476
console.log(parseInt(' 42abc')); // 42
parseInt skips spaces at the start, then reads digits until it meets one that doesn't belong, and stops there without complaining. In binary, 2 is not a digit, so '102' is read as just '10', which is 2. In hex, a, b and c are all digits, so all of '12abc' counts.
Step 5: parseInt is not Number
console.log(parseInt('1e3'), Number('1e3')); // 1 1000
Number reads the whole string, and 1e3 is short for 1 * 10 ** 3. parseInt doesn't know about exponents, so it stops at e. Use Number when the whole string must be a number. Use parseInt when you want only the leading digits.
Step 6: a base that doesn't exist
const radixResult = (r) => {
try {
return (255).toString(r);
} catch (error) {
return error.constructor.name;
}
};
console.log(radixResult(1), radixResult(37), radixResult(16)); // RangeError RangeError ff
Base 1 and base 37 throw a RangeError instead of returning something. try...catch catches the error, and error.constructor.name gives the error's type as text. Most math code in JavaScript returns NaN for bad input; this is one of the few places that throws.
Step 7: padding and round trips
Binary for small numbers is short: 5 is 101. To show a full byte (8 digits), pad it with zeros on the left.
const toBinary8 = (n) => n.toString(2).padStart(8, '0');
const roundTrip = (n, radix) => parseInt(n.toString(radix), radix);
console.log(toBinary8(5), toBinary8(200)); // 00000101 11001000
console.log((12345).toString(7), roundTrip(12345, 7)); // 50664 12345
padStart(8, '0') adds zeros until the text is 8 characters long. And for whole numbers, writing in a base and reading back with the same base always gives the original number.
Step 8: 0.1 in binary
Decimals can be written in other bases too.
console.log((0.1).toString(2).length); // 57
The full string is 0.0001100110011001100110011001100110011001100110011001101. The pattern 0011 repeats forever in true binary, but a JavaScript number has limited room, so it is cut off and rounded at the end. That is why 0.1 is never exactly 0.1 inside a computer.
The full solution
The answer panel has radixResult, toBinary8 and roundTrip, and prints the four bases, the negative number, every parseInt case, the bad radices and 0.1 in binary. Press Run to see the output.
const radixResult = (r) => {
try {
return (255).toString(r);
} catch (error) {
return error.constructor.name;
}
};
const toBinary8 = (n) => n.toString(2).padStart(8, '0');
const roundTrip = (n, radix) => parseInt(n.toString(radix), radix);
console.log('255 in four bases:', (255).toString(16), (255).toString(2), (255).toString(8), (255).toString(36));
console.log('-255 in hex :', (-255).toString(16), '<- sign and magnitude');
console.log('parseInt with 16 :', parseInt('ff', 16), parseInt('0xff', 16), parseInt('0xff'));
console.log('parseInt bare ff :', parseInt('ff'));
console.log('partly readable :', parseInt('102', 2), parseInt('12abc', 16), parseInt(' 42abc'));
console.log('1e3 two ways :', parseInt('1e3'), Number('1e3'));
console.log('bad radices :', radixResult(1), radixResult(37));
console.log('binary byte :', toBinary8(5), toBinary8(200));
console.log('0.1 in binary :', (0.1).toString(2), 'length', (0.1).toString(2).length);
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('255 is ff, 11111111, 377 and 73 in bases 16, 2, 8 and 36', [(255).toString(16), (255).toString(2), (255).toString(8), (255).toString(36)], ['ff', '11111111', '377', '73']);
test('a negative gets a minus sign, not a two-complement bit pattern', (-255).toString(16), '-ff');
test('parseInt wants the radix: bare ff is NaN, but 0xff is read as hex anyway', [parseInt('ff', 16), Number.isNaN(parseInt('ff')), parseInt('0xff')], [255, true, 255]);
test('parseInt stops at the first character the radix cannot use', [parseInt('102', 2), parseInt('12abc', 16), parseInt(' 42abc')], [2, 76476, 42]);
test('which is why parseInt is not Number: 1e3 reads as just 1', [parseInt('1e3'), Number('1e3')], [1, 1000]);
test('a radix outside 2 to 36 is a RangeError, not a NaN', [radixResult(1), radixResult(37), radixResult(16)], ['RangeError', 'RangeError', 'ff']);
test('padStart turns a binary string into a fixed-width byte', [toBinary8(5), toBinary8(200)], ['00000101', '11001000']);
test('the integer round trip through base 7 is exact', [(12345).toString(7), roundTrip(12345, 7)], ['50664', 12345]);
test('0.1 in binary repeats until the double runs out, 57 characters in', [(0.1).toString(2).slice(0, 22), (0.1).toString(2).length], ['0.00011001100110011001', 57]);
toString(radix) and parseInt(string, radix) are inverses for integers, and the round trip through any base from 2 to 36 is exact. Outside that range toString throws a RangeError, which is worth knowing because it is one of the few places in the Math area that throws instead of returning NaN.
parseInt is the loose one. It skips leading whitespace, reads as many valid digits as it can, and returns what it got: parseInt('102', 2) is 2, because 2 is not a binary digit and it stops. It also understands a 0x prefix with no radix at all. Most importantly it has no idea about exponents, so parseInt('1e3') is 1 while Number('1e3') is 1000. Reach for Number when the whole string must be a number, and parseInt only when a prefix is genuinely what you want.
(0.1).toString(2) is the best one-line proof of why decimal fractions misbehave. It prints 0.0001100110011001100110011001100110011001100110011001101 — a repeating pattern that gets cut off and rounded up at the end. There is no bug anywhere in the arithmetic; the value simply was never 0.1.
Common mistakes
- Leaving out the radix.
parseInt('ff')isNaN. Always pass the base as the second argument. - Using
parseIntto check a whole string. It ignores trailing junk, soparseInt('42abc')is 42. UseNumberif any junk should fail. - Writing
255.toString(16). That is a syntax error. Use(255).toString(16).
Try it yourself
- Turn the color
#ff8800into its red, green and blue numbers withparseIntandslice. - Write
toHex2(n)that always returns two hex digits, sotoHex2(9)is09. - What does
parseInt('z', 36)give? AndparseInt('Z', 36)? Check whether case matters.