I know there are ways to convert to Base36 with toString
or Base64 with encodeToString
. However, I would like to how to do it. For example, I am using
private static final String BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\'\"+-";
I am able to do it with int with the following code.
private String convertBase(int num) {
String text = "";
int j = (int) Math.ceil(Math.log(num) / Math.log(BASE.length()));
for (int i = 0; i < j; i++) {
text += BASE.charAt(num % BASE.length());
num /= BASE.length();
}
return text;
}
However, the numerical value of the byte[]
is bigger than long
.
Ok, I found the answer myself. I used BigInteger
to solve it.
public String baseConvert(final BigInteger number, final String charset) {
BigInteger quotient;
BigInteger remainder;
final StringBuilder result = new StringBuilder();
final BigInteger base = BigInteger.valueOf(charset.length());
do {
remainder = number.remainder(base);
quotient = number.divide(base);
result.append(charset.charAt(remainder.intValue()));
number = number.divide(base);
} while (!BigInteger.ZERO.equals(quotient));
return result.reverse().toString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.