Saturday, December 29, 2007

Hex to Decimal conversion - BASH newbie


Suppose we have a list of Hex numbers. To convert them to corresponding decimal values:

$ cat hex.txt

3EFF
32E1
A10B
10AB

$ cat hex.txt | while read hexn
> do
> let x=0x$hexn
> echo "Hex=$hexn,Decimal=$x"
> done
Hex=3EFF,Decimal=16127
Hex=32E1,Decimal=13025
Hex=A10B,Decimal=41227
Hex=10AB,Decimal=4267

Another similar way of doing:

$ while read hexn
> do
> printf "%d\n" "0x"$hexn
> done < hex.txt

And we got "bc" to do that too :-)

$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
ibase=16
3EFF
16127
quit

No comments:

© Jadu Saikia www.UNIXCL.com