4

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

for example :

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

result :

convert "0x148FA1"
x=1347489

How to do it?

3 Answers 3

12

You can convert in many different ways, all within bash, and relatively easy.

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
Sign up to request clarification or add additional context in comments.

Comments

6

You can check this link. Fundamentally below code will help you.

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

It is in pure shell scripting solution.

1 Comment

An elegant solution that doesn't rely on bash. Thanks!
1

If you have a python interpreter available, you can always do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.