Emmanuel Akinfulubi

JavaScriptBasic

Convert decimal to binary, octal and hex in JavaScript

Intermediate · 4 min read

Every day we count in base 10, with the ten digits 0 to 9. Computers work in base 2, binary, with only 0 and 1. Programmers also use base 16, hexadecimal or "hex", because it is a short way to write binary. You see hex in color codes like #FF8800, and binary in flags and permissions. Base 8, octal, still appears in file permissions like 755.

In this tutorial you will write bases(n), which turns a number into its binary, octal and hex forms, and then read each one back with parseInt. Along the way you will meet one of the oldest traps in JavaScript. You need to know what a number, a string and an object are.

What a base is

In base 10, each position is worth ten times the one to its right: 255 means 2 hundreds, 5 tens and 5 ones. In base 2, each position is worth two times the one to its right: 1, 2, 4, 8, 16 and so on. So binary 101 means one 4, no 2s and one 1, which is 5.

Base 16 needs sixteen digits, so after 9 it uses letters: A is 10, B is 11, up to F for 15. FF in hex is 15 sixteens plus 15 ones, which is 255.

The number itself never changes. Only the way it is written does.

Writing a number in another base

Every number has a toString method. Give it a base from 2 to 36, and it writes the number in that base:

JavaScript

console.log((5).toString(2));    // 101
console.log((255).toString(16)); // ff

The result is a string. The brackets around 5 are there because 5.toString would make JavaScript think the dot is a decimal point. With a variable, like n.toString(2), you don't need them.

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

33 Convert between number bases

fair

Convert a decimal number to binary, octal and hexadecimal, and read each back again.

Stuck? Three hints, smallest first
  1. 1. n.toString(2) gives binary; the argument is the base, from 2 to 36.
  2. 2. parseInt(text, 2) reads it back. Always pass the base.
  3. 3. Leaving the base off parseInt is a classic bug: a leading zero used to mean octal.

Step 1: all three bases at once

Return an object with one property per base:

Step 1

function bases(n) {
  return {
    binary: n.toString(2),
    octal: n.toString(8),
    hex: n.toString(16).toUpperCase(),
  };
}
console.log(bases(255)); // { binary: '11111111', octal: '377', hex: 'FF' }

toString(16) writes letters in lower case, ff. Hex is usually shown in capitals, so toUpperCase() tidies it.

Step 2: read it back with parseInt

parseInt(text, base) does the opposite: it reads text written in a base and gives you an ordinary number.

JavaScript

console.log(parseInt('11111111', 2)); // 255
console.log(parseInt('377', 8));      // 255
console.log(parseInt('FF', 16));      // 255

The second argument is called the radix, another word for base. Base 36 is the largest, because it uses all ten digits plus all 26 letters. That makes it handy for short IDs:

JavaScript

console.log((12345).toString(36));            // 9ix
console.log(parseInt((12345).toString(36), 36)); // 12345

Writing a number out and reading it back, and getting the same number, is called a round trip. It is a good way to test a conversion.

Step 3: always pass the base

parseInt lets you leave the base out. When you do, it looks at the text and guesses:

JavaScript

console.log(parseInt('0x1A'));     // 26: it saw 0x and guessed hex
console.log(parseInt('0x1A', 10)); // 0: told base 10, it stops at the x

0x at the start is how JavaScript code marks a hex number, so parseInt treats the text as hex. Guessing means the same function can read two similar-looking inputs in different ways. In much older JavaScript engines, a leading zero, as in '08', was also guessed to mean octal. Pass the base every time and there is nothing left to guess.

Step 4: parseInt vs Number

parseInt reads digits from the start and stops at the first character it can't use. Number is stricter: the whole text has to be a valid number, or you get NaN ("Not a Number").

JavaScript

console.log(parseInt('12abc', 10)); // 12
console.log(Number('12abc'));       // NaN

Which is better depends on the job. For text a user typed into a form, Number usually is, since '12abc' is probably a typo, not 12. For reading a number in another base, parseInt with a radix is the right tool, because Number only reads base 10 (plus prefixes like 0x).

The full solution

The complete answer has bases, converts 255 into all three forms, reads them back, does a round trip through base 36, and shows both traps: the guessed 0x prefix and parseInt reading only the start of '12abc'. Press Run to see the output.

The answer

function bases(n) {
  return {
    binary: n.toString(2),
    octal: n.toString(8),
    hex: n.toString(16).toUpperCase(),
  };
}

const out = bases(255);
console.log('255 in binary:', out.binary);
console.log('255 in octal :', out.octal);
console.log('255 in hex   :', out.hex);

// Reading back. The base argument is not optional in practice.
console.log('parseInt("11111111", 2) =', parseInt('11111111', 2));
console.log('parseInt("FF", 16)      =', parseInt('FF', 16));

// Why the base matters: without it, behaviour depends on the text.
console.log('parseInt("0x1A")     =', parseInt('0x1A'));      // hex, guessed
console.log('parseInt("0x1A", 10) =', parseInt('0x1A', 10));  // stops at the x

// And Number() is stricter than parseInt: it refuses partial input.
console.log('Number("12abc") =', Number('12abc'));
console.log('parseInt("12abc", 10) =', parseInt('12abc', 10));

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.

9 checks

test('255 in binary', out.binary, '11111111');
test('255 in octal', out.octal, '377');
test('255 in hex', out.hex, 'FF');
test('read binary back', parseInt(out.binary, 2), 255);
test('read hex back', parseInt(out.hex, 16), 255);
test('a round trip through base 36', parseInt((12345).toString(36), 36), 12345);
test('parseInt guesses hex from a 0x prefix', parseInt('0x1A'), 26);
test('but stops at the x when told base 10', parseInt('0x1A', 10), 0);
test('Number refuses partial input', Number.isNaN(Number('12abc')), true);

parseInt without a base is one of the oldest footguns in the language: it inspects the text and guesses, so '0x1A' becomes 26 while '08' once became 0 in older engines. Always pass the radix. And note the difference from Number(), which refuses '12abc' outright rather than reading the leading digits.

Common mistakes

  • Leaving the radix off parseInt. It guesses from the text. Always pass the base, even for base 10.
  • Forgetting that toString returns a string. (5).toString(2) is the text '101', not the number one hundred and one.
  • Writing 5.toString(2). JavaScript reads 5. as a decimal number and reports a syntax error. Use (5).toString(2) or a variable.

Try it yourself

  1. Pad binary to 8 digits, so 5 becomes '00000101'. (Hint: padStart(8, '0').)
  2. Turn a color like { r: 255, g: 136, b: 0 } into the hex code '#FF8800', making sure each part is two characters.
  3. Read the hex code back into its three parts using parseInt and slice.

Keep practising

Newsletter

New writing, when it lands.

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