(phixonline)-->
with javascript_semantics
constant digits = "0123456789"&
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"&
"abcdefghijklmnopqrstuvwxyz"
type base(integer b)
return b<=-1 and b>=-length(digits)
end type
function encodeNegBase(atom n, base b)
string res = iff(n?"":"0")
while n!=0 do
atom r = remainder(n,b)
n = trunc(n/b)
if r<0 then
n += 1
r -= b
end if
res &= digits[r+1]
end while
return reverse(res)
end function
function decodeNegBase(string ns, base b)
atom total = 0,
bb = 1
for i=length(ns) to 1 by -1 do
integer k = find(ns[i],digits)-1
if k=-1 or k>-b then return "invalid digit" end if
total += k*bb
bb *= b
end for
return total
end function
-- decimal, base, expected
constant tests = {{10, -2, "11110"},
{146, -3, "21102"},
{15, -10, "195"},
{-5795577,-62, "Phix"}}
for i=1 to length(tests) do
{atom n, atom b, string e} = tests[i]
string ns = encodeNegBase(n, b)
printf(1,"%9d in base %-3d is %6s\n", {n, b, ns})
atom nn = decodeNegBase(ns, b)
string ok = iff(ns=e and nn=n?""," ????")
printf(1,"%9d <--------------'%s\n",{nn,ok})
end for