【问题标题】:How to convert byte array to custom base string?如何将字节数组转换为自定义基本字符串?
【发布时间】:2016-08-01 13:16:52
【问题描述】:

我知道有一些方法可以使用 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

【问题讨论】:

  • 我建议避免在字符串上使用Math.ceilMath.log+=,但我建议处理负数。顺便说一句,您的程序将为0 打印空字符串,而不是尝试一次转换整个byte[],您可以逐步进行。例如三个字节在 base64 中变成 4 个字符。

标签: java encode


【解决方案1】:

好的,我自己找到了答案。我用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();
}

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 2013-05-08
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多