Numbers · beginner
JavaScript Program to Convert Decimal to Binary
Convert a decimal number to binary in JavaScript by repeated division by 2, then with toString(2) and padStart(), and convert back with parseInt(text, 2).
- while loop
- string building
- toString(2)
- parseInt(text, 2)
Binary (base 2) uses only the digits 0 and 1. To convert a decimal number by hand, divide by 2 repeatedly and write down the remainders; read from last to first, they are the binary digits. JavaScript also has this built in, but writing it yourself shows what the built-in does.
The program
function toBinary(n) {
if (n === 0) return "0";
let bits = "";
while (n > 0) {
bits = (n % 2) + bits;
n = Math.floor(n / 2);
}
return bits;
}
for (const n of [10, 255, 0]) {
console.log(n, "->", toBinary(n));
}10 -> 1010
255 -> 11111111
0 -> 0How it works
- n % 2 is the next binary digit, from right to left, so it is added to the front of bits.
- Adding a number to a string converts it: 0 + "" is "0".
- Math.floor(n / 2) halves n and drops the remainder: 10 → 5 → 2 → 1 → 0.
- Zero needs its own case, because the loop would not run and the result would be empty.
Watch it run line by line
Visualize toBinary(10) and watch bits grow from the left: "0", "10", "010", "1010", while n halves on every pass.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Built-in conversions
number.toString(2) converts to binary (and toString(16) to hexadecimal). padStart(8, "0") pads to eight digits, and parseInt(text, 2) converts back.
console.log((10).toString(2));
console.log((10).toString(2).padStart(8, "0"));
console.log(parseInt("1010", 2), (255).toString(16));1010
00001010
10 ffCommon mistakes
- Appending remainders (bits += …) instead of prepending them, which reverses the digits.
- Writing 10.toString(2): the dot is read as a decimal point. Use (10).toString(2) or 10..toString(2).
- Negative numbers: (-10).toString(2) is "-1010", not the two's-complement bits. Use (n >>> 0).toString(2) for 32-bit patterns.
- Converting decimals: (0.1).toString(2) prints a long, repeating binary fraction, because 0.1 has no exact binary form. That is also why 0.1 + 0.2 is not exactly 0.3.
Try it yourself
- Convert to any base from 2 to 16 using the digits "0123456789ABCDEF".
- Count the 1 bits in 255.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.