Bash Functions to Convert Between Numeric Representations

Add these to your bashrc file:

function h2d { echo “obase=10; ibase=16; $( echo “$*” | sed -e ‘s/0x//g’ -e ‘s/\([a-z]\)/\u\1/g’ )” | bc; }
function h2b { echo “obase=2; ibase=16; $( echo “$*” | sed -e ‘s/0x//g’ -e ‘s/\([a-z]\)/\u\1/g’ )” | bc; }
function b2d { echo “obase=10; ibase=2; “$*”” | bc; }
function b2h { echo “0x$(echo “obase=16; ibase=2;”$*”” | bc)”; }
function d2b { echo “obase=2; ibase=10; “$*”” | bc; }
function d2h { echo “0x$(echo “obase=16; ibase=10; “$*”” | bc)”; }

Now use as follows:

$ h2d 0xff
255

h2d means convert hexadecimal representation to decimal.
d2b means convert decimal to binary. Etc.

Leave a Reply