为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 Base64 缓冲区大小会使其大于基础文本的长度?

为什么 Base64 缓冲区大小会使其大于基础文本的长度?

Go
郎朗坤 2023-02-21 16:28:24
我正在尝试将字节数组编码为 Base64 并遇到两个问题。我可以用 来做到这一点base64.StdEncoding.EncodedLen(text),但我担心这很昂贵,所以我想看看我是否可以用 来做到这一点len(text)。这是代码(这些函数被命名为“Marshal”,因为我在 JSON 封送处理期间将它们用作字段转换器):package mainimport (    "crypto/rand"    "encoding/base64"    "fmt")func main() {    b := make([]byte, 60)    _, _ = rand.Read(b)    // Marshal Create Dst Buffer    MarshalTextBuffer(b)    // Marshal Convert to String    MarshalTextStringWithBufferLen(b)    // Marshal Convert to String    MarshalTextStringWithDecodedLen(b)}func MarshalTextBuffer(text []byte) error {    ba := base64.StdEncoding.EncodeToString(text)    fmt.Println(ba)    return nil}func MarshalTextStringWithBufferLen(text []byte) error {    ba := make([]byte, len(text)+30) // Why does len(text) not suffice? Temporarily using '30' for now, just so it doesn't overrun.    base64.StdEncoding.Encode(ba, text)    fmt.Println(ba)    return nil}func MarshalTextStringWithDecodedLen(text []byte) error {    ba := make([]byte, base64.StdEncoding.EncodedLen(len(text)))    base64.StdEncoding.Encode(ba, text)    fmt.Println(ba)    return nil}这是输出:IL5CW8T9WSgwU5Hyi9JsLLkU/EcydY6pG2fgLQJsMaXgxhSh74RTagzr6b9yDeZ8CP4Azc8xqq5/+Cgk[73 76 53 67 87 56 84 57 87 83 103 119 85 53 72 121 105 57 74 115 76 76 107 85 47 69 99 121 100 89 54 112 71 50 102 103 76 81 74 115 77 97 88 103 120 104 83 104 55 52 82 84 97 103 122 114 54 98 57 121 68 101 90 56 67 80 52 65 122 99 56 120 113 113 53 47 43 67 103 107 0 0 0 0 0 0 0 0 0 0][73 76 53 67 87 56 84 57 87 83 103 119 85 53 72 121 105 57 74 115 76 76 107 85 47 69 99 121 100 89 54 112 71 50 102 103 76 81 74 115 77 97 88 103 120 104 83 104 55 52 82 84 97 103 122 114 54 98 57 121 68 101 90 56 67 80 52 65 122 99 56 120 113 113 53 47 43 67 103 107]为什么中间的MarshalTextStringWithBufferLen需要额外的填充?是base64.StdEncoding.EncodedLen一个代价高昂的函数(比如我可以用底层函数解决它,但我担心成本)。
查看完整描述

1 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

Base-64 编码将二进制数据(每字节 8 位)存储为文本(每字节使用 6 位),因此每 3 个字节被编码为 4 个字节(3x8 = 4x6)。所以len(text) + 30在你的代码中是错误的,并且应该是len(text)*4/3(如果 len(text) 可以被 3 整除)但是为了提高可读性并避免你应该用来base64.StdEncoding.EncodedLen()获取长度的错误。

如果您查看代码,base64.StdEncoding.EncodedLen您会发现它与您自己进行计算一样快(特别是因为它是内联的)。


查看完整回答
反对 回复 2023-02-21
  • 1 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号