Code:
EXPORT basecalc()
BEGIN
local maxdigits:=20; // maximum number of digits for frac part
local j,k,t,run:=1;
local b1:=10;
local b2:=16;
local d:=0;
local n:="";
local ds:="";
local r:=string(rand,1,12); // create a random CAS variable
local var:="";
local ipn:=""; // integer part of n
local fpn:=""; // frac part of n
local digits:="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
k:=size(r)-2;
var:="tmp" + right(r,k);
while run do
t:=input(
{
{ n, [2], { 15, 80, 0 } },
{ b1, [0], { 25, 25, 1 } },
{ b2, [0], { 70, 25, 1 } },
{ maxdigits, [0], {25,25, 2 } }
},
"Base Converter",
{ "n=", "base1=", "base2=", "digits=" },
{
"Enter the integer",
"Enter the base of the integer n",
"Enter the base to convert to",
"Max allowable digits"
}
);
if t then
r:=var + ":={0,0}";
CAS(EVAL(r));
k:=size(n);
if (k AND (b1 >= 2) AND (b2 <= 62)) then
j:=instring(n,".");
if j then
if (j-1>0) then ipn:=left(n,j-1); end;
if (k-j>0) then fpn:=right(n,k-j); end;
k:=j-2;
else
ipn:=n;
k:=size(n)-1;
end;
// k = largest exponent
t:=size(ipn);
for j from 1 to t do
ds:=mid(ipn,j,1);
d:=instring(digits,ds)-1;
if ((d >= b1) OR (d < 0)) then msgbox("Invalid digit: " + ds); j:=-1; break; end;
r:=var + "[1]:=" + var + "[1]+" + d + "*" + b1 + "^" + k;
k:=k-1;
CAS(EVAL(r));
end;
if (j == -1) then continue; end;
t:=size(fpn);
for j from 1 to t do
ds:=mid(fpn,j,1);
d:=instring(digits,ds)-1;
if ((d >= b1) OR (d < 0)) then msgbox("Invalid digit: " + ds); j:=-1; break; end;
r:=var + "[2]:=" + var + "[2]+" + d + "*" + b1 + "^" + k;
k:=k-1;
CAS(EVAL(r));
end;
if (j == -1) then continue; end;
n:="";
t:=size(ipn);
if t then
r:="ip(ln(" + var + "[1])/ln(" + b2 + ")))";
k:=CAS(EVAL(r));
for j from k downto 0 do
r:="ip(" + var + "[1]/(" + b2 + "^" + j + "))";
d:=CAS(EVAL(r));
ds:=mid(digits,d+1,1);
n:=n+ds;
r:=var + "[1]:=" + var + "[1] - " + d + "*" + b2 + "^" + j;
CAS(EVAL(r));
end;
end;
t:=size(fpn);
if t then
n:=n+".";
r:="numer(" + var + "[2])"; t:=CAS(EVAL(r));
r:="denom(" + var + "[2])"; k:=CAS(EVAL(r));
for j from 1 to maxdigits do
r:="ip(" + var + "[2]*" + b2 + ")";
d:=CAS(EVAL(r));
r:=var + "[2]:=" + var + "[2]*" + b2 + "-" + d;
CAS(EVAL(r));
// floating point issue
r:=var + "[2] < 0";
if CAS(EVAL(r)) then
r:=var + "[2]:=" + var + "[2]+1";
CAS(EVAL(r));
d:=d-1;
end;
ds:=mid(digits,d+1,1);
n:=n+ds;
r:=var + "[2] == 0";
if CAS(EVAL(r)) then break; end;
end;
end;
t:=b1;
b1:=b2;
b2:=t;
else
msgbox("Invalid input");
end;
else
run:=0;
end;
end;
r:="purge(" + var + ")";
CAS(EVAL(r));
return(0);
END;