Emmanuel Akinfulubi

JavaScriptMath

Convert a number to any base with toString in JavaScript

Intermediate · 4 min read

We count in base 10 because we have ten digits, 0 to 9. Computers work in base 2 (binary), programmers read memory in base 16 (hexadecimal, or hex), and some short codes in links use base 36, which packs a big number into a few letters and digits. In JavaScript, one built-in method converts a number into any of these: toString with a radix, which is just another word for the base.

In this tutorial you will print 255 in binary, octal, hex and base 36, then try the cases that surprise people: a negative number, a fraction, and a base that is out of range. You only need to know what a number and a method are.

What a base is

In base 10, each place is worth ten times the place to its right: 255 is 2 hundreds, 5 tens and 5 ones. In base 2, each place is worth two times the one to its right (1, 2, 4, 8, 16 and so on), and the only digits are 0 and 1.

255 is 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1, every place from 1 up to 128, so in binary it is 11111111.

In base 16 the places are 1, 16, 256 and so on, and you need sixteen digits. After 0 to 9 come the letters a to f, so a means 10 and f means 15. 255 is 15 × 16 + 15, so in hex it is ff.

Calling toString on a number

To call a method on a number literal, wrap it in brackets. Without them, JavaScript reads the dot as a decimal point:

JavaScript

console.log((255).toString(16)); // ff
const n = 255;
console.log(n.toString(2));      // 11111111

With a variable you don't need the brackets. The result is always a string, not a number.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

65 Any base, with toString(radix)

fair

Print 255 in binary, octal, hex and base 36. Then find out what a negative number gives, what a fraction gives, and what happens at radix 1 and 37.

Stuck? Three hints, smallest first
  1. 1. (255).toString(16), and the radix runs from 2 to 36.
  2. 2. Digits past 9 are the lowercase letters a to z, which is why 36 is the ceiling.
  3. 3. A negative gets a minus sign in front, not a two's complement pattern. >>> 0 gives you the pattern.

Step 1: the four bases

Step 1

console.log(n.toString(2), n.toString(8), n.toString(16), n.toString(36)); // 11111111 377 ff 73

Octal (base 8) gives 377: 3 × 64 + 7 × 8 + 7 = 255. Base 36 gives 73: 7 × 36 + 3 = 255.

Step 2: the default is base 10

Step 2

console.log(n.toString(), String(n)); // 255 255

With no argument, toString() uses base 10, which is the same as String(n).

Step 3: why the limit is 36

Each digit has to be a single character. There are ten digits and twenty-six letters, so the biggest base toString can write is 36. In base 36, z is the last digit (35), and 36 rolls over to 10, just as 9 rolls over to 10 in our base:

Step 3

console.log((35).toString(36), (36).toString(36)); // z 10

Ask for base 37 and there is no character left for the 37th digit, so JavaScript throws a RangeError. Base 1 and base 0 throw too: the allowed range is 2 to 36.

Step 3 continued

let radixError = 'none';
try {
  n.toString(37);
} catch (e) {
  radixError = e.constructor.name;
}
console.log(radixError); // RangeError

try runs the code, and if it throws, catch receives the error. e.constructor.name is the name of the error's type.

Step 4: a negative number

Programmers who know C or Java often expect a negative number in binary to show the computer's internal pattern. JavaScript doesn't do that:

Step 4

console.log((-255).toString(2)); // -11111111

It simply puts a minus sign in front of the digits for 255. To see the actual 32-bit pattern a computer uses for -255 (called two's complement), first convert it with >>> 0, which reads the same bits as an unsigned (never negative) whole number:

JavaScript

const pattern = (-255 >>> 0).toString(2);     // the 32-bit two's complement bits
console.log(pattern);         // 11111111111111111111111100000001
console.log(pattern.length);  // 32
console.log(-255 >>> 0);      // 4294967041

Step 5: a fraction

toString works on fractions too:

Step 5

const tenth = (0.1).toString(2);
console.log(tenth.slice(0, 10)); // 0.00011001
console.log(tenth.length);       // 57
console.log((0.1).toString(16)); // 0.1999999999999a

0.1 has no exact binary form, just as 1/3 has no exact decimal form (0.333…). JavaScript stores the closest value it can, and toString(2) prints that stored value in full: 57 characters. The hex form shows the same thing more compactly. The repeating 9s should go on forever, but they stop and the last digit is rounded up to a. That rounding is why 0.1 + 0.2 is not exactly 0.3.

The full solution

The answer panel prints 255 in all four bases, the default radix, -255 with its minus sign and its 32-bit pattern, the base 37 error, 35 and 36 in base 36, and 0.1 in binary and hex. Press Run to see the output.

The answer

const n = 255;

let radixError = 'none';
try {
  n.toString(37);
} catch (e) {
  radixError = e.constructor.name;
}

const pattern = (-255 >>> 0).toString(2);     // the 32-bit two's complement bits
const tenth = (0.1).toString(2);

console.log('255 in 2, 8, 16, 36:', n.toString(2), n.toString(8), n.toString(16), n.toString(36));
console.log('default radix      :', n.toString(), 'same as String(n):', String(n));
console.log('-255 in binary     :', (-255).toString(2), '<- a sign, not two\'s complement');
console.log('the actual bits    :', pattern, 'which is', -255 >>> 0);
console.log('radix 37           :', radixError);
console.log('35 and 36 in base 36:', (35).toString(36), (36).toString(36));
console.log('0.1 in binary      :', tenth);
console.log('0.1 in hex         :', (0.1).toString(16));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('255 in binary, octal, hex and base 36', [n.toString(2), n.toString(8), n.toString(16), n.toString(36)], ['11111111', '377', 'ff', '73']);
test('with no argument the radix is 10, matching String(n)', [n.toString(), String(n)], ['255', '255']);
test('a negative gets a minus sign, not a two\'s complement pattern', (-255).toString(2), '-11111111');
test('the pattern needs >>> 0 first, and is 32 bits wide', [pattern, pattern.length], ['11111111111111111111111100000001', 32]);
test('radix 37 throws a RangeError, and so does radix 1', radixError, 'RangeError');
test('base 36 runs 0-9 then a-z, so 35 is z and 36 rolls over to 10', [(35).toString(36), (36).toString(36)], ['z', '10']);
test('a fraction gets a point and an expansion of the actual double', [tenth.slice(0, 10), tenth.length], ['0.00011001', 57]);
test('0.1 in hex ends in a, which is where the rounding went', (0.1).toString(16), '0.1999999999999a');

toString(radix) is the whole conversion, for 2 to 36 — ten digits plus twenty-six letters, and nothing left for a 37th. Anything outside that range is a RangeError, including 0 and 1.

Two results surprise people. A negative number is rendered as a minus sign followed by the magnitude's digits: (-255).toString(2) is '-11111111', not the two's complement bits a C programmer expects. Coerce with >>> 0 first to get the 32-bit pattern. And a fraction is expanded honestly — (0.1).toString(2) prints 53 significant bits of the double that 0.1 actually is, which is why it runs to 57 characters and why the hex form ends in a. That expansion is the same fact as exercise 11, written in a base that cannot hide it.

Common mistakes

  • Writing 255.toString(16) without brackets. JavaScript reads 255. as a number with a decimal point, and the line is a syntax error. Write (255).toString(16).
  • Expecting a negative number to show its bit pattern. (-255).toString(2) is -11111111. Use (-255 >>> 0).toString(2) for the 32-bit pattern.
  • Forgetting the result is a string. (255).toString(16) + 1 is 'ff1', not a bigger number.

Try it yourself

  1. Print the numbers 0 to 16 in binary and look at how the digits roll over.
  2. Find what number zz in base 36 is, using parseInt('zz', 36), then turn it back with toString(36).
  3. Print (0.5).toString(2) and (0.25).toString(2). Why are these short when 0.1 is so long?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.