Converting values from base 10 to a given base and vice versa


It is often necessary to convert a value from base 10 to the equivalent of that value in another base, or vice versa.

The first example below converts from a given base to base 10. The second example converts from base 10 to a given base.

data _null_; 
   retain possdigs '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
   length basedig $1;
   input digits $ base;
   digits=upcase(digits);
   l=length(digits); 
   j=0; 
   sum=0;
   do i=l to 1 by -1; 
      basedig=substr(digits,i,1); 
      k=index(possdigs,basedig)-1;                 
      sum+(k * base**j);         
      j+1; 
   end; 
   put digits= base= sum=; 
   datalines;
1234  10 
ff    16
1111  2 
ABCDEZZZZ 36
;
run;

/* output */

DIGITS=1234 BASE=10 SUM=1234
DIGITS=FF BASE=16 SUM=255
DIGITS=1111 BASE=2 SUM=15
DIGITS=ABCDEZZZ BASE=36 SUM=808334375615


data _null_; 
   retain possdigs '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
   input base10 newbase;
   do power=0 to 100 while(newbase**power<=base10);  end;
   left=base10; 
   length digits $10; 
   digits=' '; 
   i=0; 
   do power=power-1 to 0 by -1; 
      i+1; 
      r=int(left/(newbase**power));
      substr(digits,i,1)=substr(possdigs,r+1,1); 
      left=left-(newbase**power)*r;
   end;
   put base10= newbase= digits=;
   datalines;
1234 10 
255 2 
255 16 
36 36 
37 36 
;
run;

      /* output */     

BASE10=1234 NEWBASE=10 DIGITS=1234
BASE10=255 NEWBASE=2 DIGITS=11111111
BASE10=255 NEWBASE=16 DIGITS=FF
BASE10=36 NEWBASE=36 DIGITS=10
BASE10=37 NEWBASE=36 DIGITS=11