Objective: Convert a number in decimal representation to hexadecimal format in a shell script.
So, let’s say that we have a variable d
that has a value of 255 (decimal).
1 |
$ d=255 |
To convert the representation to hex, we can use one of the following methods. The first method is by using bc
. Note that the obase
tells bc
the base of the output number. The input base is by default 10 or decimal.
1 2 |
$ echo "obase=16; $d"| bc FF |
The next method is to use printf
. The output can either be lowercase or uppercase depending on the format specifier used.
1 2 |
$ printf "%x\n" $d ff |
1 2 |
$ printf "%X\n" $d FF |