【问题标题】:Buffer sizing during Unmarshal for Base64 makes it too large?在 Unmarshal for Base64 期间调整缓冲区大小使其太大?
【发布时间】:2022-10-01 08:56:52
【问题描述】:

我正在尝试将字节数组编码为 Base64 并遇到两个问题。这是代码:

package main

import (
    \"crypto/rand\"
    \"encoding/base64\"
    \"fmt\"
)

func main() {
    b := make([]byte, 60)
    _, _ = rand.Read(b)

    // Unmarshal Create Dst Buffer
    UnmarshalTextBuffer(b)

    // Unmarshal Convert to String
    UnmarshalTextStringWithBufferLen(b)

    // Unmarshal Convert to String
    UnmarshalTextStringWithDecodedLen(b)
}

func UnmarshalTextBuffer(text []byte) error {
    ba := base64.StdEncoding.EncodeToString(text)
    fmt.Println(ba)
    return nil
}

func UnmarshalTextStringWithBufferLen(text []byte) error {
    ba := make([]byte, len(text)+30) // Why does len(text) not suffice?
    base64.StdEncoding.Encode(ba, text)
    fmt.Println(ba)
    return nil
}

func UnmarshalTextStringWithDecodedLen(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]

为什么中间的UnmarshalTextStringWithBufferLen 需要额外的填充?

base64.StdEncoding.EncodedLen 是不是一个代价高昂的函数(例如我可以用底部函数解决它,但我担心代价)。

  • base64 编码的数据比原始数据大。使用函数 base64.StdEncoding.EncodedLen 从原始数据计算编码数据的大小。 EncodedLen documentation 链接方法的source code。与编码数据的总成本相比,该功能并不昂贵。
  • 谢谢!如果您将此添加为答案,我很乐意接受。
  • 我写评论是因为我认为我可以提供帮助,但我不明白你的具体问题。三个问题提出了不同的问题(标题,最后两段各一个)。标题更像是一个陈述,似乎与问题中 base64 包的实际使用无关(解组类似于解码,而不是编码)。编辑问题以使其更加集中。

标签: go base64


【解决方案1】:

Base-64 编码将二进制数据(每字节 8 位)存储为文本(每字节使用 6 位),因此每 3 个字节编码为 4 个字节(3x8 = 4x6)。所以len(text) 应该是len(text)*4/3(如果 len(text) 可以被 3 整除)但是为了提高可读性和避免错误,你应该使用base64.StdEncoding.EncodedLen。它与自己进行计算一样快,甚至更快。

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    相关资源
    最近更新 更多