Shell Script: Convert Decimal to Hex

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).

$ 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.

$ 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.

$ printf "%x\n" $d
ff
$ printf "%X\n" $d
FF

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react, vuejs); plays_on(xbox, ps4); linux_desktop_user(true); }