如何计算Base64编码的字符串长度?

时间:2018-04-03 15:01:45

标签: java base64

我已阅读following topic并在那里找到了这个公式:

length = 4*(n/3)

我开始测试它:

1个符号: Base64.getEncoder().encodeToString("1".getBytes()) => MQ==(4个符号)

2个符号: Base64.getEncoder().encodeToString("12".getBytes()) => MTI=(4个符号)

5个符号: Base64.getEncoder().encodeToString("12345".getBytes()) => MTIzNDU=(8个符号)

8个符号: Base64.getEncoder().encodeToString("12345678".getBytes()) => MTIzNDU2Nzg=(12个符号)

21symbols: Base64.getEncoder().encodeToString("123456789012345678901".getBytes()) => MTIzNDU2Nzg5MDEyMzQ1Njc4OTAx(28个符号)

看起来这个公式不起作用。

你能解释mu结果吗?

2 个答案:

答案 0 :(得分:2)

64位(2 6 )一位数可以代表6位。 因此,4位数字恰好可以代表4 * 6位= 3个字节。

(使用÷进行显式整数除法:)

对于n个字节,需要4 *(n÷3)个数加上余数n%3(0 <3个字节),需要0到4个数字:

0 bytes (0 bits)    0 digits
1 byte  (8 bits)    2 digits (12 bits)     + "=="
2 bytes (16 bits)   3 digits (18 bits)     + "="

通常使用=填充最多4位/填充字符。 这不能是0,然后会添加一个字节0x0。

然后公式为4 * Math.ceil(n / 3.0)

没有填充:Math.ceil(n * 8 / 6.0) = Math.ceil(n * 4 / 3.0) = (n * 4 + (3 - 1)) ÷ 3

在java中,只能使用int division:

int base64Length(byte[] b) {
    int n = b.length;
    return (n * 4 + 2)/3;
}

答案 1 :(得分:-1)

尝试长度= 4 *((n / 3)+ 1),其中“/”是整数除法。

编辑:Lexicore是正确的,我的公式在余数为零时失败。

int length = 4 * (n / 3);
if (n % 3 > 0) length++;