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.
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:
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.
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
Leave a Reply