Objective: Convert a number in hexadecimal representation to decimal format in a shell script
Let’s say that we have a variable h
that has a value of 0xFF
(hexadecimal).
$ h=FF
To convert the representation to decimal, we can use one of the following methods. The first method is by using bc
. Note that the ibase
tells bc
the base of the input number. The output base is by default 10 or decimal.
$ echo "ibase=16; $h"| bc 255
The next method is to use printf
. The 0x
prefix is required to indicate that it’s a hexadecimal number.
$ printf "%d\n" 0x${h} 255
$ printf "%d\n" 0xFF 255
On bash shell, you can use the the following expressions. A leading 0x
denotes hexadecimal. Otherwise, numbers take the form of [base#]n
where [base#]
is a decimal number representing the arithmetic base, and n
is a number in that base.
$ echo $((16#ff)) 255
$ echo $((0xff)) 255
$ echo $((0x$h)) 255
$ echo $((16#$h)) 255