在阅读base64维基之后…
我想知道这个公式是怎么运作的
给定一个长度为n的字符串,base64的长度为
即:4*Math.Ceiling(((double)s.Length/3)))
我已经知道base64的长度必须是%4==0,以允许解码器知道原始文本的长度。
序列的最大填充数可以是=或==。
wiki:每个输入字节的输出字节数大约是4 / 3 (33%) 开销)
问题:
以上信息是如何与输出长度相匹配的?
在阅读base64维基之后…
我想知道这个公式是怎么运作的
给定一个长度为n的字符串,base64的长度为
即:4*Math.Ceiling(((double)s.Length/3)))
我已经知道base64的长度必须是%4==0,以允许解码器知道原始文本的长度。
序列的最大填充数可以是=或==。
wiki:每个输入字节的输出字节数大约是4 / 3 (33%) 开销)
问题:
以上信息是如何与输出长度相匹配的?
当前回答
我在其他回答中没有看到简化的公式。逻辑是覆盖的,但我想要一个最基本的形式为我的嵌入式使用:
Unpadded = ((4 * n) + 2) / 3
Padded = 4 * ((n + 2) / 3)
注意:当计算无填充计数时,我们四舍五入整数除法,即加上除数-1,在这种情况下是+2
其他回答
对于所有会说C语言的人,看看这两个宏:
// calculate the size of 'output' buffer required for a 'input' buffer of length x during Base64 encoding operation
#define B64ENCODE_OUT_SAFESIZE(x) ((((x) + 3 - 1)/3) * 4 + 1)
// calculate the size of 'output' buffer required for a 'input' buffer of length x during Base64 decoding operation
#define B64DECODE_OUT_SAFESIZE(x) (((x)*3)/4)
从这里拍的。
我认为给出的答案忽略了原始问题的重点,即需要分配多少空间来适合长度为n字节的给定二进制字符串的base64编码。
答案是((n / 3) + 1) * 4 + 1
这包括填充和终止空字符。如果你在做整数运算,你可能不需要楼层调用。
Including padding, a base64 string requires four bytes for every three-byte chunk of the original string, including any partial chunks. One or two bytes extra at the end of the string will still get converted to four bytes in the base64 string when padding is added. Unless you have a very specific use, it is best to add the padding, usually an equals character. I added an extra byte for a null character in C, because ASCII strings without this are a little dangerous and you'd need to carry the string length separately.
在我看来,正确的公式应该是:
n64 = 4 * (n / 3) + (n % 3 != 0 ? 4 : 0)
下面是一个函数来计算一个base64编码文件的原始大小为KB的字符串:
private Double calcBase64SizeInKBytes(String base64String) {
Double result = -1.0;
if(StringUtils.isNotEmpty(base64String)) {
Integer padding = 0;
if(base64String.endsWith("==")) {
padding = 2;
}
else {
if (base64String.endsWith("=")) padding = 1;
}
result = (Math.ceil(base64String.length() / 4) * 3 ) - padding;
}
return result / 1000;
}
每个字符代表6位(log2(64) = 6)。
因此用4个字符表示4 * 6 = 24位= 3个字节。
所以你需要4*(n/3)个字符来表示n个字节,这需要四舍五入到4的倍数。
由于四舍五入到4的倍数而导致的未使用填充字符的数量显然是0、1、2或3。