为什么在Base64编码中使用填充? [英] Why padding is used in Base64 encoding?

查看:816
本文介绍了为什么在Base64编码中使用填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Possible Duplicate:
Why does base64 encoding requires padding if the input length is not divisible by 3?

引用维基百科


...解码时这些填充字符必须丢失,但
允许计算未编码文本的有效
长度,当它的
输入二进制长度不会是3个字节的
倍数。 ...

...these padding characters must then be discarded when decoding but still allow the calculation of the effective length of the unencoded text, when its input binary length would not be a multiple of 3 bytes. ...

但是,即使剥离填充字符,也可以轻松完成原始数据长度的计算。

But the calculation of length raw data can easily be done even if strip the padding character.

          |               Encoded
          |--------------------------------------
Raw Size  | Total Size | Real Size | Padding Size
1         | 4          | 2         | 2
2         | 4          | 3         | 1
3         | 4          | 4         | 0
4         | 8          | 6         | 2
5         | 8          | 7         | 1
6         | 8          | 8         | 0
7         | 12         | 10        | 2
8         | 12         | 11        | 1
9         | 12         | 12        | 0
10        | 16         | 14        | 2
.
.
.

所以给出真实的编码大小(第三列),你可以随时正确地猜测什么是填充尺寸:

So given the real encoded size (third column) you can always correctly guess what padded size would be:

PaddedSize = 4 * Ceil (RealSize / 4)

所以在理论上,没有必要填充。算法会处理它。考虑到Base64编码是受欢迎的行业标准,它被用于许多应用和设备。这些将从减少的编码大小中受益。所以问题是,为什么在Base64编码中使用填充?

So in theory, there was no need of padding. Algorithm would have handled it. Considering that Base64 encoding is a popular industry standard, it is used in many applications and devices. These would have benefited from reduced encoded size. So question is, why padding is used in Base64 encoding?

推荐答案

它使编码消息的整数倍为4个字符。这可能会使编写一个解码器容易一些。您可以加载和处理4的块中的字符,并将其转换为3个输出字符,而填充可以轻松实现,而无需关闭字符串的末尾。

It makes the encoded message an integer multiple of 4 characters. This might make writing a decoder slightly easier. You can load and process characters in blocks of 4 and convert them to 3 output characters, and the padding makes it easy to do this without going off the end of the string.

这篇关于为什么在Base64编码中使用填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆