Create a function 'baseXtoY' which:
converts an integer or string n
, which is a base x
number (hexadecimal, binary, etc)
into a base y
number, reliably, including numbers like 10e50
or higher, using the least bytes possible, and using the following constraints:
- Provide built-in support for bases up to 64 using the following sequence: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=/
- Provide support for bases higher than 64 by allowing a different sequence to be used in the input
- Provide support for multi-byte sequences eg ('aa','bb','cc'...) in cases rally high value bases are needed (could also support unicode instead)
- You cannot have a base less than 2. Show an error
- You cannot use any built-in functions that convert base to base for you
- You need not worry about floating point
parameters should be:
n
- any number, as a stringx
- the base ofn
, integery
- the base of the return values1
- the sequence the given number's base usess2
- the sequence the desired base usesb
- the bytesize of the digits ins1
- return value should be a string
example inputs:
using '88888'
base 10 to 2: baseXtoY('88888',10,2) >>> '10101101100111000'
base 2 to 5: baseXtoY('10101101100111000',2,5) >>> '10321023'
base 5 to 32: baseXtoY('10321023',5,32) >>> '2mpo'
base 32 to 10, using a new sequence, s=the above 64bit sequence, a=the alphabet: baseXtoY('2mpo',32,10,s,a) >>> 'hhhhh'
base 5 to 10, input base uses more than 1 byte per digit: baseXtoY('bbaaddccbbaaccdd',5,10,('aa','bb','cc','dd','ee'),'0123456789',2))
> '88888'`
you do not have to inlude the character length of the testing or input code, just the function(s).
edit: I've given up trying to shorten my Python code lower than the answers, so I'll just show what I have. 585 characters python 2.7
r=range
def b1(n,x,s):
if n==0:return s[0]
if x<=1:raise
l=[];p=n;i=0
while 1:
y=x**i;l.append(y)
if y>p:break
else:i+=1
l.reverse();f=[]
for p in l:h=int(n//p);f.append(h);n-=h*p
while f[0]==0:f.pop(0)
q=''
for p in r(len(f)):q+=s[f[p]]
return q
def b2(n,x,s,b):
n=list(str(n));l=[]
while n:
a=''
for p in r(b):a+=n.pop(0)
l.append(a)
m=0;q=0
while l:c=s.index(l.pop());q+=c*(x**m);m+=1
return q
s=''.join(map(chr,r(48,58)+r(97,123)+r(65,91)))+'=/'
def baseXtoY(n,x=10,y=2,s1=s,s2=s,b=1):return n if x==y else b2(n,x,s1,b)if y==10 else b1(b2(n,x,s1,b),y,s2)
test cases:
32 10 5 >>> 112
112 5 2 >>> 100000
100000 2 10 >>> 32
88888 10 5 0123456789 ('aa', 'bb', 'cc', 'dd', 'ee') 1 >>> bbaaddccbbaaccdd
bbaaddccbbaaccdd 5 10 ('aa', 'bb', 'cc', 'dd', 'ee') 0123456789 2 >>> 88888