hexadecimal

Hexadecimal conversion in bash/awk

Let’s suppose we have a number expressed in given base (i.e. “E0″ in hexadecimal). How can we convert it to decimal using bash or other common Unix tools? And what if we need to perform an any-to-any base conversion?

First way: printf + hexdump

We can tell bash that a given string is just a disguised hexadecimal number by adding “\x” at the top of it and then using the built-in printf function to recover the number:

$ foo="6F"
$foo2="\x"$foo
$ printf "%b" $foo2 | hexdump -e '1/1 "%d" "\n"'
111
$ printf "%b" $foo2 | hexdump -e '1/1 "%o" "\n"'
157

Please notice that %d makes hexdumo to return a signed integer; if you need an unsigned integer just replace it with %u: