Convert hex to decimal with shell script

I need to convert a number from hexadecimal to decimal using a shell script

eg:

convert()
{
    ...
    echo x=$decimal
}

      

result:

convert "0x148FA1"
x=1347489

      

How to do it?

+3


source to share


3 answers


You can convert in many ways, within bash, and relatively easily.

To convert a number from hexadecimal to decimal:



$ echo $((0x15a))
346

$ printf '%d\n' 0x15a
346

$ perl -e 'printf ("%d\n", 0x15a)'
346

$ echo 'ibase=16;obase=A;15A' | bc
346

      

+9


source


You can check the link. Basically the code below will help you.

h2d(){
  echo "ibase=16; $@"|bc
}
d2h(){
  echo "obase=16; $@"|bc
}

      



It is in pure scripting solution.

+6


source


If you have a python interpreter, you can always:

#!/bin/sh
x="0x23"
val=`python -c "print int('$x', 16)"`
echo $val

      

+1


source







All Articles