如何将字节数组转换为自定义基本字符串?

How to convert byte array to custom base string?

我知道有一些方法可以使用 toString 转换为 Base36 或使用 encodeToString 转换为 Base64。但是,我想知道怎么做。例如,我正在使用

private static final String BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \'\"+-";

我可以通过以下代码使用 int 来完成。

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;
}

但是byte[]的数值大于long

好的,我自己找到了答案。我用BigInteger解决了

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();
}