Convert binary to decimal recursively in JavaScript
Intermediate · 4 min read
Computers store everything as 1s and 0s. A string like '1101' is a number written in binary, base 2, and in everyday base 10 it means 13. Converting between the two comes up when you read file formats, network flags, color values and permission bits.
In this tutorial you will write binaryToDecimal(bits) recursively, check its input properly, and see why JavaScript's own parseInt can quietly give you a wrong answer on bad input. You need to know strings, functions and if. Binary and recursion are both explained from zero.
How binary works
In the decimal numbers you use every day, each place is worth ten times the one to its right: ones, tens, hundreds. In binary, each place is worth two times the one to its right: ones, twos, fours, eights.
bits: 1 1 0 1
worth: 8 4 2 1
total: 8 + 4 + 0 + 1 = 13
A 1 means "count this place" and a 0 means "skip it".
The recursive idea
Here is a neat way to see it. Take '1101'. The last digit, 1, is the ones place. Everything before it, '110', is a binary number too, worth 6. Because every place has moved one step to the left, it counts double:
'1101' = 1 + 2 × '110'
'110' = 0 + 2 × '11'
'11' = 1 + 2 × '1'
'1' = 1 + 2 × ''
'' = 0
A function that solves a problem by calling itself on a smaller piece is recursive. The empty string, worth 0, is the base case where it stops.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
11 Binary to decimal
fairConvert a string of 1s and 0s to a number, recursively. Then compare your answer with parseInt on bad input.
Stuck? Three hints, smallest first
- 1. Work from the right: the last digit is worth 1, and everything before it is worth twice as much.
- 2. Or from the left:
value = value * 2 + digitat each step. - 3. Reject anything that is not a 1 or a 0 before converting, because the built-ins do not agree on what to do.
Step 1: convert from the right
bits[bits.length - 1] is the last character, and Number turns '1' into 1. slice(0, -1) is everything except the last character:
function convert(bits) {
if (bits.length === 0) return 0;
const last = Number(bits[bits.length - 1]);
return last + 2 * convert(bits.slice(0, -1));
}
console.log(convert('1101')); // 13
console.log(convert('10000')); // 16
console.log(convert('11111111')); // 255
console.log(convert('0001101')); // 13
Leading zeros don't change anything, just as 007 is 7 in decimal.
Step 2: see what bad input does
Try a string with a 2 in it, which isn't a binary digit:
function convert(bits) {
if (bits.length === 0) return 0;
const last = Number(bits[bits.length - 1]);
return last + 2 * convert(bits.slice(0, -1));
}
console.log(convert('1102')); // 14
The function happily treats the 2 as a value and returns 14, a number that looks perfectly reasonable and is meaningless. Bad input should be refused, not converted.
Step 3: check the input first
A regular expression is a pattern for matching text. /^[01]+$/ means: from the start (^) to the end ($), one or more (+) characters that are each 0 or 1. test returns true if the whole string matches:
function convert(bits) {
if (bits.length === 0) return 0;
const last = Number(bits[bits.length - 1]);
return last + 2 * convert(bits.slice(0, -1));
}
function binaryToDecimal(bits) {
if (!/^[01]+$/.test(bits)) throw new SyntaxError('binary digits only');
return convert(bits);
}
console.log(binaryToDecimal('1101')); // 13
try {
binaryToDecimal('1102');
} catch (e) {
console.log(e.constructor.name); // 'SyntaxError'
}
The check lives in binaryToDecimal, which runs once. The recursive convert doesn't repeat it on every call. Because of the +, the empty string is refused too.
Step 4: what the built-ins do
JavaScript can already convert binary. parseInt(text, 2) reads text in base 2. But look at what it does with the same bad input:
console.log(parseInt('1101', 2)); // 13
console.log(parseInt('1102', 2)); // 6
console.log(Number('0b1102')); // NaN
console.log((13).toString(2)); // '1101'
parseInt reads '110', stops at the 2, and returns 6 with no warning. Number with the 0b prefix at least gives NaN, "not a number", so you can tell something went wrong. toString(2) goes the other way, from a number to binary text.
That quiet stop-at-the-first-bad-character habit is behind many parseInt bugs. Checking the input yourself removes the whole problem.
Step 5: convert from the left
You can also read the digits from the left, keeping a running total. At each digit, double the total and add the digit:
const fromLeft = (bits, acc = 0) =>
bits.length === 0 ? acc : fromLeft(bits.slice(1), acc * 2 + Number(bits[0]));
console.log(fromLeft('1101')); // 13
console.log(fromLeft('11111111')); // 255
For '1101' the total goes 1, 3, 6, 13. acc is short for accumulator, the running total carried from call to call.
The full solution
The panel has the checked converter, the left-to-right version, and checks that compare both with parseInt and show how the built-ins treat '1102'. Press Run to see the output.
function binaryToDecimal(bits) {
if (!/^[01]+$/.test(bits)) throw new SyntaxError('binary digits only');
return convert(bits);
}
// From the right: last digit is the 1s place, the rest is worth double.
function convert(bits) {
if (bits.length === 0) return 0;
const last = Number(bits[bits.length - 1]);
return last + 2 * convert(bits.slice(0, -1));
}
// From the left, which needs no slicing arithmetic at the end.
const fromLeft = (bits, acc = 0) =>
bits.length === 0 ? acc : fromLeft(bits.slice(1), acc * 2 + Number(bits[0]));
const rejected = (() => {
try { binaryToDecimal('1102'); return 'no error'; } catch (e) { return e.constructor.name; }
})();
console.log("'1101' ->", binaryToDecimal('1101'));
console.log("'11111111' ->", binaryToDecimal('11111111'));
console.log('--- what the built-ins do with the invalid "1102" ---');
console.log("parseInt('1102', 2) =", parseInt('1102', 2), '<- silently stops at the 2 and returns 6');
console.log("Number('0b1102') =", Number('0b1102'), '<- NaN, which at least tells you');
console.log('ours =', rejected, '<- refuses outright');
Output
12 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 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("'0' is 0", binaryToDecimal('0'), 0);
test("'1' is 1", binaryToDecimal('1'), 1);
test("'1101' is 13", binaryToDecimal('1101'), 13);
test("'10000' is 16", binaryToDecimal('10000'), 16);
test("'11111111' is 255", binaryToDecimal('11111111'), 255);
test('leading zeros do not matter', binaryToDecimal('0001101'), 13);
test('the left-to-right version agrees', ['0', '1', '1101', '10000', '11111111'].every((b) => fromLeft(b) === binaryToDecimal(b)), true);
test('it agrees with parseInt on valid input', binaryToDecimal('1101'), parseInt('1101', 2));
test('and with toString(2) going back', (13).toString(2), '1101');
test('invalid input is refused', rejected, 'SyntaxError');
test('whereas parseInt quietly returns 6 for "1102"', parseInt('1102', 2), 6);
test('and Number gives NaN', Number.isNaN(Number('0b1102')), true);
The conversion is the easy half. The useful half is the disagreement on bad input: parseInt('1102', 2) reads 110, stops at the 2, and hands back 6 with no complaint — a wrong number that looks like a right one. Number('0b1102') at least gives NaN. Validating with /^[01]+$/ first costs one line and removes the whole class of problem. This is the general shape of most parseInt bugs: it is happy to parse a prefix.
Common mistakes
- Trusting
parseInton user input. It returns a number for'1102'. Check with/^[01]+$/first. - Forgetting
Number.bits[0]is the string'1', and'1' + 2 * 6joins text to give'112'instead of adding. - Reading the places in the wrong direction. The rightmost digit is the ones place. Doubling from the wrong end gives the wrong number for anything that isn't symmetrical.
Try it yourself
- Write
decimalToBinary(n)recursively. (Hint: the last bit isn % 2, and the rest isMath.floor(n / 2).) - Extend the converter to hexadecimal, base 16, where the digits go
0to9and thenatof. - Find the decimal value of the largest 8-digit binary number, then check it with
(255).toString(2).