Bill Allombert on Wed, 25 Jul 2012 17:51:39 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Reading numbers in other formats.


On Wed, Jul 25, 2012 at 05:09:31PM +0200, Manolo wrote:
> I have a stupid problem with last version of PARI-GP, when reading
> hexadecimal numbers in compiled way.
> 
> For example, the famous code:
> 
> ------
> hextodec(s) =
>     { local(v=Vec(s), a=10,b=11,c=12,d=13,e=14,f=15,
>                       A=10,B=11,C=12,D=13,E=14,F=15, h);
> 
>       for(i=1,#v,h = (h<<4) + eval(v[i])); h
>     }
> ---------
> 
> works ok when captured as a gp function (say: read("hextodec.gp")):
> 
> ? hextodec("1af9")
> %1 = 6905
> 
> But when I run
> 
> $ gp2c-run -g hextodec.gp
> 
> I obtain:
> 
> ? hextodec("1af9")
> %1 = 256*a + (16*f + 4105)
> 
> Any clue?

See gp2c documentation section 4.2

<http://pari.math.u-bordeaux.fr/pub/pari/manuals/gp2c/gp2c.html#htoc18>

" Also the functions {read, eval, kill} may compile fine but have a
surprising behaviour in some case, because they may modify the state of the GP
interpreter, not of the compiled program."

eval() use the GP evaluator which is not aware of the value of the C variables.

I suggest you use instead:
hextodec(s)=
{
  local(v:vecsmall=Vecsmall(s),h:int=0);
  for(i=1,#v,h = (h<<4) + if(v[i]<=57,v[i]-48,if(v[i]<=70,v[i]-55,v[i]-87)));h
}

Cheers,
Bill.