Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!uunet!mcsun!hafro!isgate!krafla!karlth From: karlth@rhi.hi.is (Karl Thoroddsen) Newsgroups: comp.lang.pascal Subject: Re: Brain Teaser Summary: Does a solution exist? Message-ID: <1207@krafla.rhi.hi.is> Date: 16 Oct 89 13:18:18 GMT References: <727@thor.wright.EDU> <1989Oct5.213548.13466@wuee1.wustl.edu> Organization: University of Iceland Lines: 53 In article <1989Oct5.213548.13466@wuee1.wustl.edu>, jtw@wuee1.wustl.edu (Trent Wohlschlaeger) writes: > In article <727@thor.wright.EDU> demon@thor.wright.edu writes: > > Write a routine that will convert from one base to another. > >function convert(base : integer; input_num : string) : string; > ^^^^ > > Might I suggest: > > function convert(inbase, outbase : integer; input_num : string) : string; > > I would be more impressed with code that does this directly, rather > than converting to base 10 (or 2, or 16, or...) first. > > For example, convert 10110101 base 4 to x base 7. > > x:= convert (4, 7, "10110101"); > > Trent A solution to the problem of converting from one base to another is fairly straightforward (solution follows). But as Trent says it would be much more impressive if the routine would convert directly, can anyone program a routine which does that? -----------------------CONVERT ROUTINE TP 5.0------------------ {FOR BASE >1 and <17} function power(x,y:longint):longint; var pow : longint; begin pow:=1; while y>0 do begin pow:=pow*x;dec(y);end; power:=pow; end; function convert(in_base,out_base:integer;in_num:string):string; const num_char = '0123456789ABCDEF'; var count,sum,num:longint;Out_num:string; begin sum:=0;count:=1;num:=0;Out_num:=''; while not(count>length(in_num)) do begin num:=pos(copy(in_num,count,1),num_char)-1; sum:=num*power(in_base,length(in_num)-count)+sum; inc(count);{ count:=count+1} end; { Of convert to 10 base} while sum>0 do begin out_num:=concat(copy(num_char,(sum mod out_base)+1,1),out_num); sum:=sum div out_base; end; convert:=out_num; end;