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

后端 未结 11 1469
粉色の甜心
粉色の甜心 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:29

    This code works:

    public class Convert {
    
        public static void main(String[] args) {
            int num= 2147483647;
            String text="ABCD1";
    
    
            System.out.println("num: " + num + "=>" + base10ToBase36(num));
            System.out.println("text: " +text + "=>" + base36ToBase10(text));
        }
    
        private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz";
    
        //"0123456789 abcdefghij klmnopqrst uvwxyz"
        //"0123456789 0123456789 0123456789 012345"
    
    
        private static String max36=base10ToBase36(Integer.MAX_VALUE); 
    
        public static String base10ToBase36(int inNum) {
            if(inNum<0) {
                throw new NumberFormatException("Value  "+inNum +"  to small");
            }
            int num = inNum;
            String text = "";
            int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length()));
            for(int i = 0; i < j; i++){
                text = codeBase36.charAt(num%codeBase36.length())+text;
                num /= codeBase36.length();
            }
            return text;
        }
        public  static int base36ToBase10(String in) {
            String text = in.toLowerCase();
            if(text.compareToIgnoreCase(max36)>0) {
                throw new NumberFormatException("Value  "+text+"  to big");
            }
    
            if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){
                throw new NumberFormatException("Value "+text+" false format");
            }
            int num=0;
            int j = text.length();
            for(int i = 0; i < j; i++){
                num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i);
                text = text.substring(0,text.length()-1);
            }
            return num;
        }
    
    
    }
    

提交回复
热议问题