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

后端 未结 11 1454
粉色の甜心
粉色の甜心 2020-11-29 04:55

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

11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 05:34

    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 = "";
    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;
    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);
    }
    

提交回复
热议问题