1833831 Members
2539 Online
110063 Solutions
New Discussion

Re: Convert Hex to Dec

 
Chris Frangandonis
Regular Advisor

Convert Hex to Dec

Hi,

I have a problem with my script, which does convert hex to dec with incorrect values
Part of my scripts reads:
decnum7 = 0
for (i=1;i {
tposOP = index(hexstr,substr(OPE,i,1))-1
decnum7=decnum7+((16**(slen7 -i))*tposOP)
} }
printf ("\n0%s %.2d

When using /usr/bin/printf "%d\n" 0xd3fe9906 it returns with error:
printf: Error converting 0xd3fe9906
2147483647 and when visa-visa /usr/bin/printf "%x\n??? 3556677894 it returns d3fe9906??? which is correct. My maxdsiz is set at 2063835136. Is there a better solution besides PERL or C++ that I can use in my script for converting?

Many Thanks
Chris
6 REPLIES 6
James R. Ferguson
Acclaimed Contributor

Re: Convert Hex to Dec

Hi Chris:

You could leverage 'bc' and awk's 'system' function. For example:

# awk 'END {system("echo obase=16\;2^39-1|bc")}' < /dev/null

...would output:

7FFFFFFFFF

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Convert Hex to Dec

Hi Chris:

Sorry, you wanted the inverse. Therefore, by example (again):

# awk 'END {system("echo ibase=16\;7FFFFFFFFF|bc")}' < /dev/null

...which returns the decimal number:

549755813887

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: Convert Hex to Dec

If you don't want to use Perl then another utility to consider is bc (or dc). Both will do unlimited range/precision calculations.

Warning: 0xNNNN is not understood nor is fe4 (rather than FE4).

As an example do this:
bc
obase=16
ibase=10
FF
quit

Still my preference would be perl.

If it ain't broke, I can fix that.
Leif Halvarsson_2
Honored Contributor

Re: Convert Hex to Dec

Hi,
Try to print a unsigned integer instead, it works.

# /usr/bin/printf "%u\n" 0xd3fe9906
3556677894
Chris Frangandonis
Regular Advisor

Re: Convert Hex to Dec

Hi JRF and A.Clay

A.Clay perl is nice, but I am in the learning stages.
JRF I did try bc but not in that fashion (good one). Now how could I apply it wih my script as below:
???.
???..
decnum7 = 0
for (i=1;i{
tposOP = index(hexstr,substr(OPE,i,1))-1
decnum7=decnum7+((16**(slen7 -i))*tposOP)
}
printf ("\n0%s %.2d????????????..

Thanks Once again
Chris
James R. Ferguson
Acclaimed Contributor

Re: Convert Hex to Dec

Hi (again) Chris:

OK, if you like the 'bc' approach, I propose define the hex-string you want converted in an awk variable of your choice. Then, again, by way of example, "print" it thusly:

# awk -v VAR=FFF 'END {$0="echo ibase=16\;"VAR"|bc";system($0)}' < /dev/null

Note that the hexadecimal string *must* be *uppercase* characters. Hence, setting VAR=fff would fail -- 'bc' thinks the "fff" is a variable!

You can easily circumvent this, too:

# awk -v VAR=fff 'END {VAR=toupper(VAR);$0="echo ibase=16\;"VAR"|bc";system($0)}' < /dev/null

(...perverse enough, I think...)

Regards!


,,,JRF...