Bash shell Decimal to Binary base 2 conversion

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})


General method for converting an integer number into another representation with another base (but base<=10 because of using digits 0..9 for representation, only):

function convertIntvalToBase () # (Val Base)
{
   val=$1
   base=$2
   result=""
   while [ $val -ne 0 ] ; do
        result=$(( $val % $base ))$result #residual is next digit
        val=$(( $val / $base ))
   done
   echo -n $result
}

e.g.

convertIntvalToBase $ip1 2     # converts $ip1 into binary representation

You can use bc as:

echo "obase=2;$ip1" | bc

See it


Decimal to binary conversion in Bash:

I'm using Ubuntu 14.04 to do this.

Convert the decimals 1 through 5 to binary.

el@apollo:~$ bc <<< "obase=2;1"
1
el@apollo:~$ bc <<< "obase=2;2"
10
el@apollo:~$ bc <<< "obase=2;3"
11
el@apollo:~$ bc <<< "obase=2;4"
100
el@apollo:~$ bc <<< "obase=2;5"
101

Bonus example:

el@apollo:~$ bc <<< "obase=2;1024"
10000000000

el@apollo:~$ bc <<< "obase=2;2^128"
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000