Reputation: 65
I know that we can convert hex to dec in bash using
#!/bin/bash
echo "Type a hex number"
read hexNum
echo $(( 16#$hexNum ))
but when I run it with hexNum=9b4bbba36e494bcd
, it gives me -7256500063973061683
i.e negative value, which is 2's complement.
I don't want it's 2 complement. I want output for hexNum=9b4bbba36e494bcd
as 11190244009736489933
. As given on https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=9b4bbba36e494bcd
How can I get this output using bash? Please help!
Upvotes: 2
Views: 2874
Reputation: 27185
As pointed out in the comments, the number in your example is too big. bash
does calculations with fixed size integers. Big numbers will overflow.
bc
supports arbitrary large numbers and can do a base conversion too. However, bc
requires hexadecimal numbers to be written in UPPERCASE, therefore you have to convert your input first. bash
has a built-in parameter substitution to convert to upper case:
hex=9b4bbba36e494bcd
echo "ibase=16; ${hex^^}" | bc
Upvotes: 9