Convert a decimal value into the binary representation and vice versa in Bash using only built-ins. If you know a better way, please let me know. To ensure a properly formatted expression for the arithmetic expansion in bin2dec, the dec2bin function prefixes zeros as needed to pad to a character count evenly divisible by 8.

dec2bin () {
    num="$1"
    bin=""
    padding=""
    base2=(0 1)
    while [ "$num" -gt 0 ];
    do
            bin=${base2[$(($num % 2))]}$bin
            num=$(($num / 2))
    done
    if [ $((8 - (${#bin} % 8))) -ne 8 ]; then
            printf -v padding '%*s' $((8 - (${#bin} % 8))) ''
            padding=${padding// /0}
    fi
    echo $padding$bin
}


bin2dec () {
        echo $((2#$1))
}

Examples:

user@host:~$ dec2bin 1
00000001
user@host:~$ bin2dec 00000001
1
user@host:~$ dec2bin 255
11111111
user@host:~$ bin2dec 11111111
255
user@host:~$ bin2dec 1010101010101010
43690
user@host:~$ dec2bin 43690
1010101010101010

Perhaps not the most efficient way, but at least for small numbers it appears to be quicker than opening a subshell.

user@host:~$ time dec2bin 43690
1010101010101010

real    0m0.001s
user    0m0.000s
sys 0m0.000s
user@host:~$ time echo "obase=2;43690" | bc
1010101010101010

real    0m0.002s
user    0m0.000s
sys 0m0.000s
Categories:Bash
Published on :Posted on

2 thoughts on “Bash Snippet: Decimal to Binary Conversion”

·

function decbin {
liczba=$1

if [ $liczba -ge 65535 ]; then
liczba=`expr $liczba – 65535`
fi
# 2B representation
for i in 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
do
reszta=`expr $liczba % 2`
wektor[i]=$reszta
liczba=`expr $liczba / 2`
done

echo ${wektor[*]} | tr ‘ ‘ ”
}

·

The dec2bin function can be simplified a fair bit.

as follows

dec2bin () {
for((num=$1;num;num/=2))
do
bin=$((num%2))$bin
done
printf “%08d\n” $bin
}

Post your comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.