I\'m looking for an easy way in Bash to convert a decimal number into a binary number. I have variables that need to be converted:
$ip1 $ip2 $ip3 $ip4
Convert decimal to binary with bash builtin commands (range 0 to 255):
D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
echo ${D2B[7]}
00000111
echo ${D2B[85]}
01010101
echo ${D2B[127]}
01111111
To remove leading zeros, e.g. from ${D2B[7]}:
echo $((10#${D2B[7]}))
111
This creates an array with 00000000 00000001 00000010 ... 11111101 11111110 11111111 with bash‘s brace expansion. The position in array D2B represents its decimal value.
See also: Understanding code ({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})