Converting decimal numbers to binary in Bash is straightforward using the bc (basic calculator) command. This is especially useful for scripting, network calculations, or low-level debugging.
The core trick uses obase=2 to set binary output in bc. For example, to convert a single number:
echo "obase=2; 42" | bc # Output: 101010
To generate a formatted list—like 8-bit binary strings for numbers 1 to 127—use this one-liner:
for num in {1..127}; do binnum=$(echo "obase=2;$num" | bc); printf "%08d\n" "$binnum"; done
This outputs:
00000001 00000010 00000011 ... 01111111
How it works:
obase=2tells bc to output in binary.printf "%08d"pads the result to 8 digits with leading zeros.- The loop uses Bash’s
{1..127}range syntax for clean iteration.
Note: Replace {1..127} with any range (e.g., {0..255} for a full byte) or a single variable like $my_decimal.
This method requires only standard Unix tools (bc and printf), making it portable across Linux, macOS, and FreeBSD. If you’re working with binary data in scripts—like parsing flags, network masks, or permissions—this pattern is incredibly handy.
For more Bash text manipulation tricks (like handling multi-line input correctly), see my guide on why Bash echo ignores here-documents.
If you write Bash scripts regularly, “Bash Cookbook” by Carl Albing and JP Vossen is an excellent reference. It covers everything from number conversions to advanced text processing—with real-world examples you can adapt immediately.
