Thursday, May 17, 2012

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
Sample output:
4095
To convert to hexadecimal, set obase to 16, enter:
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; $@"|bc
}
d2h(){
echo "obase=16; $@"|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 "%x\n" 4095
Sample outputs:
fff
To convert hex to decimal, you'd type:
printf "%d\n" 0xfff
Sample outputs:
4095
You can save result to a shell variable and print it using printf or echo command:
output=$(printf "%d\n" 0xfff)
echo "${output}"
printf "%d\n" $output

No comments:

Post a Comment