In Java how do you convert a decimal number to base 36?

If I have a decimal number, how do I convert it to base 36 in Java?


Solution 1:

Given a number i, use Integer.toString(i, 36).

Solution 2:

See the documentation for Integer.toString

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int,%20int)

toString

public static String toString(int i, int radix)
....
The following ASCII characters are used as digits:

   0123456789abcdefghijklmnopqrstuvwxyz

What is radix? You're in luck for Base 36 (and it makes sense)
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#MAX_RADIX

public static final int     MAX_RADIX   36

Solution 3:

The following can work for any base, not just 36. Simply replace the String contents of code.

Encode:

int num = 586403532;
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(code.length()));
for(int i = 0; i < j; i++){
    //i goes to log base code.length() of num (using change of base formula)
    text += code.charAt(num%code.length());
    num /= code.length();
}

Decode:

String text = "0vn4p9";
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
int num = 0;
int j = text.length();
for(int i = 0; i < j; i++){
    num += code.indexOf(text.charAt(0))*Math.pow(code.length(), i);
    text = text.substring(1);
}