Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal To Decimal in Shell Script

People also ask

How to convert hex to decimal in bash?

'%d' format specifier is used in printf method to convert any number to decimal number. Create a bash file named hextodec3.sh and add the following code. According to this script, a hex number will be taken as input and it is used in printf method with %d to print the decimal value.


To convert from hex to decimal, there are many ways to do it in the shell or with an external program:

With bash:

$ echo $((16#FF))
255

with bc:

$ echo "ibase=16; FF" | bc
255

with perl:

$ perl -le 'print hex("FF");'
255

with printf :

$ printf "%d\n" 0xFF
255

with python:

$ python -c 'print(int("FF", 16))'
255

with ruby:

$ ruby -e 'p "FF".to_i(16)'
255

with node.js:

$ nodejs <<< "console.log(parseInt('FF', 16))"
255

with rhino:

$ rhino<<EOF
print(parseInt('FF', 16))
EOF
...
255

with groovy:

$ groovy -e 'println Integer.parseInt("FF",16)'
255

Dealing with a very lightweight embedded version of busybox on Linux means many of the traditional commands are not available (bc, printf, dc, perl, python)

echo $((0x2f))
47

hexNum=2f
echo $((0x${hexNum}))
47

Credit to Peter Leung for this solution.


One more way to do it using the shell (bash or ksh, doesn't work with dash):

echo $((16#FF))
255

Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.

One more that's not on his list:

[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816

But if all you want to do is subtract, why bother changing the input to base 10?

[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$ 

The dc command is "desk calc". It will also take input from stdin, like bc, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.

In the commands above we've got the following:

  • 16i -- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.
  • BFCA3000 -- your initial number
  • 17FF -- a random hex number I picked to subtract from your initial number
  • - -- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stack
  • p -- print the last item on the stack. This doesn't change the stack, so...
  • 10o -- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".
  • p -- print the last item on the stack again ... this time in hex.

You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.