Bash shell Decimal to Binary base 2 conversion

69,886

Solution 1

You can use bc as:

echo "obase=2;$ip1" | bc

See it

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

Defined as a function in bash:

# to Binary:
toBinary(){
    local n bit
    for (( n=$1 ; n>0 ; n >>= 1 )); do  bit="$(( n&1 ))$bit"; done
    printf "%s\n" "$bit"
}
Share:
69,886
Daniel Del Core
Author by

Daniel Del Core

Updated on July 09, 2022

Comments

  • Daniel Del Core
    Daniel Del Core almost 2 years

    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
    

    Is there a simple method to do this without looking at every individual number?

    I would prefer not to have to write a lot of code.

  • Daniel Del Core
    Daniel Del Core about 12 years
    At the moment i have echo "obase=2;$ip1" | bc echo "obase=2;$ip2" | bc echo "obase=2;$ip3" | bc echo "obase=2;$ip4" | bc and the echo each line is outputing a newline. is there a way to have it output tip to tail
  • codaddict
    codaddict about 12 years
    @DanielDC: You can do: echo "obase=2;10;20;30" | bc | tr -d '\n'
  • codaddict
    codaddict about 12 years
    @DanielDC: Add a | tr -d '\n' at the end.
  • Daniel Del Core
    Daniel Del Core about 12 years
    lol i totally forgot the | tr -d '\n' thanks heaps for your help man appreciate it
  • mklement0
    mklement0 almost 12 years
    Great solution; a slightly more compact (and marginally better-performing) version is: bc <<<"obase=2;$ip1".
  • Malte Skoruppa
    Malte Skoruppa over 9 years
    Very nice pure bash solution! To generalize this for range 0 to 2^n-1, use eval D2B='('$(for ((i=0; i<$n; i++)); do printf '%s' "{0..1}"; done)')' (after setting n). The only drawback is that this method takes O(2^n) space (superpolynomial!). This quickly draws unwieldy.
  • domih
    domih over 6 years
    Incredible tight solution! Can you explain what happens? What does {0..1} ?
  • domih
    domih over 6 years
    The output of echo $D2B is 00000000 which was confusing me, as this does not look like an array but a simple string. Thank you for enlightening me!
  • Cyrus
    Cyrus over 6 years
    @domih: Here D2B is an array. I do not recommend using $D2B because it is intended to display strings. To access the first element of an array use ${D2B[0]}.
  • Casey
    Casey about 6 years
    This is a great solution. The explanation is that bc is a calculator which accepts input from stdin. In this case, the input is the string to set the base of the output to 2 (presumable the default input is base 10), and then just echo the number in the "ip1" variable. The <<< is just a quick way to pass a string or variable to somethings stdin (ie. it is equivelent to echo "obase=2;$ip1" | bc (but presumably preferred since it eliminates the call to echo). A more straightforward example of bc adding two and two is bc <<<"2+2".
  • Paul Razvan Berg
    Paul Razvan Berg almost 6 years
    In case you're looking for the reversal process, ie binary to decimal, here you go echo $((2#$@)) where $@ is your binary number.
  • Gabriel Staples
    Gabriel Staples about 2 years
    How do you specify the number of digits?
  • Gabriel Staples
    Gabriel Staples about 2 years
  • Victor Zamanian
    Victor Zamanian about 2 years
    Any reason for using printf "%s\n" "$bit" rather than just echo $bit?
  • done
    done about 2 years
    Many reasons. Please read Why is printf better than echo?.
  • Victor Zamanian
    Victor Zamanian about 2 years
    Ew, yeah that's compelling enough I guess.