PARI/GP --- Converting Calculated Output to Binary

379 Views Asked by At

I am new to using PARI/GP.

I would like to be able to make certain computations which PARI displays in decimal form (that is fine). But I want in the next step to convert the output to binary form with the same level of precision (I specify) that was used in the original computation.

PARI has a `binary' function but it displays the answer as a boxed sequence. I would like to display the output in ordinary form.

Can somebody advise me as to how this may be accomplished?

Thank you.

3

There are 3 best solutions below

1
On BEST ANSWER

The following code (binr() for reals, bin() for reals or integers):

binr(x)=my(v=apply(y->concat(apply(x->Str(x) ,y)), binary(x+0.))); concat([v[1],".", v[2]]);
bin(n)=if(type(n)=="t_INT",concat(apply(x->Str(x),binary(n))),binr(n));

may do what you want. So, for example after you enter the code for "binr(x)" and "bin(n)" then type

\p9
bin(543)

which produces

"1000011111"

and then try

 bin(1.375)

which produces

"1.0110000000000000000000000000000"

The real precision of 9 decimal digits is the minimum, but you can set it to higher precision. Also, to get rid of the double quotes, just use "print()". For example,

print(bin(12345))

produces

11000000111001

There are probably other ways to do what you want depending on your exact situation. For example, if you just want to print the binary expansion of a specific number, then you can use this code:

apply(x->print1(x),binary(12345));

which produces the same result using only built-in functions.

2
On
? n=2^77+7
%3 = 151115727451828646838279
?
? b=binary(n)
%4 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
?
? for(i=1,#b,print1(b[i]))
100000000000000000000000000000000000000000000000000000000000000000000000000111
0
On

The first answer is great, here is the GP-Pari script to convert from the binary string back into decimal.

{dec(S)=
local(L,pt,s,sz,i,p);
L=Vec(S);
pt=0;
p=1/2;
s=0;
sz=matsize(L)[2];
for(i=1,sz,
  if(pt==0,
    if(L[i]==".",pt=1;);
    if(L[i]=="1",s=2*s+1;);
    if(L[i]=="0",s=2*s;);
  ,
    if(L[i]=="1",s+=p;);
    p/=2;
  );
);
if(pt==1,s*=1.0);
return(s);
}