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

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

    If you dont want to use Integer.toString(Num , base) , for instance, in my case which I needed a 64 bit long variable, you can use the following code: Using Lists in JAVA facilitates this conversion

    long toBeConverted=10000; // example, Initialized by 10000
    List charArray = new ArrayList();
    List charArrayFinal = new ArrayList();
    int length=10; //Length of the output string
    long base = 36;
    
                while(toBeConverted!=0)
                {
                    long rem = toBeConverted%base;
                    long quotient = toBeConverted/base;
                    if(rem<10)
                        rem+=48;
                    else
                        rem+=55;
                    charArray.add((char)rem);
                    toBeConverted=quotient;
                }
                // make the array in the reverse order
                for(int i=length-1;i>=0;--i){
                    if(i>=charArray.size()){
                        charArrayFinal.add((char) 48); // sends 0 to fix the length of the output List
                    } else {
                        charArrayFinal.add(charArray.get(i));
                    }
    
                }
    

    Example:

    (278197)36=5YNP

提交回复
热议问题