Binary to hexadecimal and decimal in a shell script

It's fairly straightforward to do the conversion from binary in pure bash (echo and printf are builtins):

Binary to decimal

$ echo "$((2#101010101))"
341

Binary to hexadecimal

$ printf '%x\n' "$((2#101010101))"
155

Going back to binary using bash alone is somewhat more complex, so I suggest you see the other answers for solutions to that.


Assuming that by binary, you mean binary data as in data with any possible byte value including 0, and not base-2 numbers:

To convert from binary, od (standard), xxd (comes with vim) or perl's unpack come to mind.

od -An -vtu1 # for decimal
od -An -vtx1 # for hexadecimal

xxd -p # for hexa

perl -pe 'BEGIN{$\="\n";$/=\30};$_=unpack("H*",$_)' # like xxd -p

# for decimal:
perl -ne 'BEGIN{$\="\n";$/=\30;$,=" "}; print unpack("C*",$_)'

Now, to convert back to binary, awk (standard), xxd -r or perl's pack:

From the decimal output from od -tu1 or perl above:

LC_ALL=C awk '{for (i = 1; i <= NF; i++) printf "%c", $i}'
perl -ape '$_=pack("C*",@F)'

From the hexa perl or xxd -p above:

xxd -r -p
perl -pe 'chomp;$_=pack("H*",$_)'

You can use bc for this by manipulating the ibase and obase parameters:

The trick is that you need to be explicit about the bases. So if your ibase is 2, then if you set your obase to 10, it won't do anything, as 10 in binary is 2. Hence you need to use hexadecimal notation.

So binary to decimal would be (watch that obase is A)

Binary to decimal:

$> echo 'ibase=2;obase=A;11110001011010'|bc
15450

Binary to hex:

$> echo 'ibase=2;obase=10000;11110001011010'|bc
3C5A

If the 'output base' obase is changed first, it should be easier:

$> echo 'obase=10;ibase=2;11110001011010'|bc
15450
$> echo 'obase=16;ibase=2;11110001011010'|bc
3C5A