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).
1 |
$ 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.
1 2 |
$ 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.
1 2 |
$ printf "%d\n" 0x${h} 255 |
1 2 |
$ 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.
1 2 |
$ echo $((16#ff)) 255 |
1 2 |
$ echo $((0xff)) 255 |
1 2 |
$ echo $((0x$h)) 255 |
1 2 |
$ echo $((16#$h)) 255 |