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

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

    First you have to convert your number it into the internal number format of Java (which happens to be 2-based, but this does not really matter here), for example by Integer.parseInt() (if your number is an integer less than 2^31). Then you can convert it from int to the desired output format. The method Integer.toString(i, 36) does this by using 0123456789abcdefghijklmnopqrstuvwxyz as digits (the decimal digits 0-9 and lower case english letters in alphabetic order). If you want some other digits, you can either convert the result by replacing the "digits" (for example toUpperCase), or do the conversion yourself - it is no magic, simply a loop of taking the remainder modulo 36 and dividing by 36 (with a lookup of the right digit).

    If your number is longer than what int offers you may want to use long (with Long) or BigInteger instead, they have similar radix-converters.

    If your number has "digits after the point", it is a bit more difficult, as most (finite) base-X-numbers are not exactly representable as (finite) base-Y-numbers if (a power of) Y is not a multiple of X.

提交回复
热议问题