Convert decimal to binary recursively
Build the binary digits of a non-negative integer as a decimal-looking number.
function decToBinary(num) { return num === 0 ? 0 : (num % 2) + 10 * decToBinary(Math.floor(num / 2)); }
Input & expected output
Input
10Expected output
1010The edge case
Input
0Expected output
0Know the limits
- The result is a number whose digits are bits, so the lab stops at 65,535 to stay exact. For real work use num.toString(2).
- The original ~~ truncation is replaced with Math.floor.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Convert decimal to binary recursively from the original 1loc collection by Nguyen Huu Phuoc, with philosophercode. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses Math.floor instead of ~~ and caps input so the digit number stays exact. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clamp a number to a range — Keep a number inside an inclusive minimum and maximum.
- Round to a number of digits — Apply decimal scaling and JavaScript rounding for display-oriented values.
- Add an ordinal suffix to a number — Append st, nd, rd or th to a positive integer.