Convert numeric into an alphanumeric value based o

2019-06-22 15:56发布

问题:

It is easy to transform a number into a alphanumeric value based on radix 16 in SAS by using the $HEX format. Now i'm looking for an easy way to do this with radix 36 (10 numerals & 26 letters).

Examples:

  • 100 -> '2s'
  • 2000 -> '1jk'
  • 30000 -> 'n5c'
  • 400000 -> '8kn4'

In Java you can do this by Integer.toString(mynumber, 36). Any ideas how to do this in SAS Base?

回答1:

Unfortunately there is easy way to do it usings formats, but the following data step should solve the problem. It works for positive integers only.

data _null_;
 infile cards;
 input innumber;
 number = innumber;
 format base $32.;
 alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 if number = 0 then base = '0';
 else
  do while (number ne 0);
   mod = mod(number, length(alphabet));
   div = floor(number / (length(alphabet)));
   base = cats(substr(alphabet,mod+1,1),base);
   number = div;
  end;
 put innumber= base=;
cards;
0
100
2000
30000
400000
;
run;


回答2:

There is no built-in functionality for this. You can iteratively modulo 36 your number, then divide by 36 until what remains is zero. To convert the sequence of modulos you get you have to add 48decimal or 30hex to get the ascii-character in case of the digits 0-9 and 101decimal or 65hex to get the ascii-character in the case of the digits A-Z.



回答3:

I suggest using PROC FCMP to create your own function that does the formatting. Then you can reuse the code whenever you want:

proc fcmp outlib=sasuser.funcs.Radix36;
   function Radix36(innumber) $ 32; /* returns character string, length 32 */
     number = innumber;
     format base $32.;
     alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     if number = 0 then base = '0';
     else do while (number ne 0);
        mod = mod(number, length(alphabet));
        div = floor(number / (length(alphabet)));
        base = cats(substr(alphabet,mod+1,1),base);
        number = div;
     end;
     return (base);
   endsub;
run;

/*****************************************************/
options cmplib=sasuser.funcs; /* add to search path */
data _null_;
input innumber;
 base = Radix36(innumber); /* call function */
 put innumber= base=;
datalines;
0
100
2000
30000
400000
;
run;


标签: sas