Linux / UNIX: Convert Hexadecimal to Decimal Number

How do I convert hex number to decimal number using a shell script under UNIX / Linux operating systems?

Hexadecimal (hex) is a numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or a through f) to represent values ten to fifteen.

bc – An arbitrary precision calculator language

There is no need to write a shell script. You can simply use the following syntax at the shell prompt to convert hex to decimal number or vice versa.

bc: Hexadecimal or Binary Conversion

To convert to decimal, set ibase to 16, enter:

echo "ibase=16; hex-number"|bc
echo "ibase=16; FFF"|bc

echo "ibase=16; hex-number"|bc
echo "ibase=16; FFF"|bc

Sample output:

4095

To convert to hexadecimal, set obase to 16, enter:

echo "obase=16; decimal-number"|bc
echo "obase=16; 10"|bc

echo "obase=16; decimal-number"|bc
echo "obase=16; 10"|bc

Sample output:

A

ibase and obase define the conversion base for input and output numbers under bc. The default for both input and output is base 10. Add following function to your ~/.bashrc:

h2d(){
  echo "ibase=16; [email protected]"|bc
}
d2h(){
  echo "obase=16; [email protected]"|bc
}

h2d(){
echo "ibase=16; [email protected]"|bc
}
d2h(){
echo "obase=16; [email protected]"|bc
}

The above two functions can be used from the command line as follows:
$ h2d 100
$ d2h AC

Base conversion using printf shell builtin

You can also use printf a shell builtin as well as /usr/bin/printf. To convert decimal to hex, you’d type:

printf "%xn" 4095

printf "%xn" 4095

Sample outputs:

fff

To convert hex to decimal, you’d type:

printf "%dn" 0xfff

printf "%dn" 0xfff

Sample outputs:

4095

You can save result to a shell variable and print it using printf or echo command:

output=$(printf "%dn" 0xfff)
echo "${output}"
printf "%dn" $output

output=$(printf "%dn" 0xfff)
echo "${output}"
printf "%dn" $output

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.