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"|bcSample output:
echo "ibase=16; FFF"|bc
4095To convert to hexadecimal, set obase to 16, enter:
echo "obase=16; decimal-number"|bcSample output:
echo "obase=16; 10"|bc
Aibase 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(){The above two functions can be used from the command line as follows:
echo "ibase=16; $@"|bc
}
d2h(){
echo "obase=16; $@"|bc
}
$ 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" 4095Sample outputs:
fffTo convert hex to decimal, you'd type:
printf "%d\n" 0xfffSample outputs:
4095You 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