- Sum
8 + 2 = 10
Convert Binary to Decimal in JavaScript
What you’ll learn
- How positional notation turns a binary bit pattern into a decimal integer.
- Two JavaScript styles: digit peel (integer that looks like
101010) and Horner on a string of"0"/"1". - Why integer doubling beats
Math.pow(2, i)here, how to validate digits, and a browser live preview withparseInt(..., 2).
Overview
Binary uses powers of two from the rightmost bit (least significant). This page shows the same math two ways in JavaScript: peel digits from a “binary-looking” integer, or scan a string of '0' and '1' characters with Horner’s rule.
Two scripts
Digit peel (reference style, fixed) plus string Horner.
Live preview
Type a bit string; see decimal via parseInt(..., 2) for a quick check.
Fixes vs naive Math.pow
Exact integer weights, digit checks, and awareness of Number safe range.
Prerequisites
Loops, integer division and modulo, and the idea of place value (ones, twos, fours, …).
console.log,Number.isInteger, and string indexing for Example 2.- Optional:
parseInt(s, 2)and binary literals0b…(ES2015).
What does binary to decimal mean?
Each bit position i (starting at 0 on the right) contributes bi · 2i where bi ∈ {0, 1}. The decimal value is the sum of those contributions.
The reference stores the pattern as a normal decimal integer 101010 so each base-ten digit is one bit; the loop reads bits from right to left.
Expanded form
Reading 101010 from most to least significant bit (left to right as written),
10101021·25 + 0·24 + 1·23 + 0·22 + 1·21 + 0·20 = 32 + 8 + 2 = 42.
Intuition
- Sum
4 + 2 + 1 = 7
Takeaway: each 1 flips on a power of two; each 0 skips that power.
Live preview
Enter a string of 0 and 1 characters (optional spaces). Uses parseInt(s, 2) for a quick decimal value. Empty or invalid characters are rejected.
Algorithm (digit-stored form)
Goal: interpret a nonnegative integer whose decimal digits are only 0 or 1 as a binary pattern and return its decimal value.
Start value = 0, weight 1
Weight will double each step: 1, 2, 4, …
While the working number is nonzero
Take d = n % 10. If d is not 0 or 1, reject. Else add d * weight to value.
Shift
Divide n by 10, multiply weight by 2, repeat.
String form (Horner)
Scan the string left to right: value = value * 2 + (c === '1' ? 1 : 0) for each c in '0' or '1'.
📜 Pseudocode
function binaryDigitsToDecimal(n): // n has only 0/1 decimal digits
value ← 0
weight ← 1
while n > 0:
d ← n mod 10
if d not in {0, 1}: return error
value ← value + d * weight
n ← floor(n / 10)
weight ← weight * 2
return valueDigit peel (integer 101010, no Math.pow)
Matches the reference flow but uses an exact doubling weight instead of Math.pow(2, i), validates digits, and keeps the sum in a normal Number for typical bit lengths.
/** @param {number} n nonnegative integer, digits only 0 or 1 */
function isBinaryDigitForm(n) {
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) {
return false;
}
if (n === 0) {
return true;
}
let t = n;
while (t > 0) {
const d = t % 10;
if (d > 1) {
return false;
}
t = Math.floor(t / 10);
}
return true;
}
/** Converts e.g. 101010 (decimal digits) to 42; returns -1 on invalid input */
function binaryDigitsToDecimal(binaryForm) {
if (!isBinaryDigitForm(binaryForm)) {
return -1;
}
let value = 0;
let weight = 1;
let n = binaryForm;
while (n > 0) {
const digit = n % 10;
value += digit * weight;
n = Math.floor(n / 10);
weight *= 2;
}
return value;
}
const binaryForm = 101010;
const dec = binaryDigitsToDecimal(binaryForm);
if (dec < 0) {
console.log("Invalid binary digit pattern.");
} else {
console.log("Binary (digit form):", binaryForm);
console.log("Decimal:", dec);
}Explanation
The least significant decimal digit of 101010 is the least significant binary bit, so the first peeled digit pairs with weight 1, then 2, then 4, and so on.
weight *= 2;Exact powers of two. Replaces Math.pow(2, i) without floating point.
if (d > 1) return false;Reject invalid “binary” digits. A digit 2–9 must not be treated as a bit.
Horner’s method on a bit string
Natural when input arrives as text: scan most-significant bit first without reversing.
/** @param {string | null | undefined} s */
function binaryStringToDecimal(s) {
if (s == null || s.length === 0) {
return -1;
}
let v = 0;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c !== "0" && c !== "1") {
return -1;
}
v = v * 2 + (c === "1" ? 1 : 0);
}
return v;
}
const bits = "101010";
const dec = binaryStringToDecimal(bits);
if (dec < 0) {
console.log("Invalid binary string.");
} else {
console.log("Binary (string):", bits);
console.log("Decimal:", dec);
}Explanation
Each step doubles the running value (shift left in binary) and adds the new bit.
v = v * 2 + (c === "1" ? 1 : 0);Horner update. Same idea as v = (v << 1) | bit for integer bit variables in lower-level languages.
Optimization
Bit shifts. When you already have validated 0/1 ints, (value << 1) | bit (with a mask) can replace multiply-add on 32-bit-friendly paths—mind signed << rules in JavaScript.
Library path. For whole-string conversion, parseInt(s, 2) or Number.parseInt(s, 2) is built in; respect length and safe-integer limits, or use BigInt('0b' + s) for long patterns.
Interview: explain both LSD peel and Horner; mention validation and overflow.
❓ FAQ
🔄 Input / output examples
Example 1 prints the digit-form value and decimal. Example 2 prints the string and decimal.
| Input form | Meaning | Decimal |
|---|---|---|
101010 (number) | Six-bit pattern | 42 |
"101010" string | Same pattern | 42 |
102 | Invalid digit 2 | Error / -1 in sample |
Edge cases and pitfalls
Confusing the digit-stored integer with a binary literal is the main conceptual trap; invalid digits and safe-integer limits are the main engineering traps.
101010 in source code
That token is a decimal integer unless you use the 0b binary literal prefix. The peel routine interprets its decimal digits as bits.
Values outside {0,1}
Without validation, a digit like 9 would be treated as 9 · 2k in the peel loop—nonsense for binary.
Math.pow(2, i)
Can mis-round for large i. Prefer integer doubling or exact shifts.
Very long bit strings
Horner on Number overflows past exact integer range; use BigInt or chunk the problem.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
Digit peel or Horner on k bits | O(k) | O(1) |
Both sample scripts use only a few scalars besides input storage.
Summary
- Math: sum of
bi 2ifor bitsbi. - Code: digit peel with doubling weight, or Horner on a string; avoid naive
Math.powfor exact integers. - Watch-outs: meaning of
101010in source, digit validation, andNumberprecision on long patterns.
The pattern 101010 in base two means 32 + 8 + 2 = 42 in base ten. In the first sample, that pattern is stored as the ordinary decimal integer 101010 so each base-ten digit is a binary bit; it is not the JavaScript binary literal 0b101010 (which already equals 42 in source code).
9 people found this page helpful
