在阅读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%) 开销)
问题:
以上信息是如何与输出长度相匹配的?
当前回答
在windows中-我想估计mime64大小的缓冲区的大小,但所有精确的计算公式都不适合我-最后我得到了这样的近似公式:
Mine64字符串分配大小(近似) =((4 *((二进制缓冲区大小)+ 1))/ 3)+ 1)
所以最后+1 -它用于ascii- 0 -最后一个字符需要分配来存储零结束-但为什么“二进制缓冲区大小”是+1 -我怀疑有一些mime64终止字符?或者这可能是一些对齐问题。
其他回答
当其他人都在讨论代数公式时,我宁愿用BASE64本身来告诉我:
$ echo "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."| wc -c
525
$ echo "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." | base64 | wc -c
710
因此,3个字节由4个base64字符表示的公式似乎是正确的。
简单的javascript实现
function sizeOfBase64String(base64String) {
if (!base64String) return 0;
const padding = (base64String.match(/(=*)$/) || [])[1].length;
return 4 * Math.ceil((base64String.length / 3)) - padding;
}
下面是一个函数来计算一个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;
}
如果n%3不为零,我相信这个是正确答案,不是吗?
(n + 3-n%3)
4 * ---------
3
Mathematica版本:
SizeB64[n_] := If[Mod[n, 3] == 0, 4 n/3, 4 (n + 3 - Mod[n, 3])/3]
玩得开心
GI
在我看来,正确的公式应该是:
n64 = 4 * (n / 3) + (n % 3 != 0 ? 4 : 0)