gpt4 book ai didi

go - 如何从base64编码字符串中获取原始文件大小

转载 作者:数据小太阳 更新时间:2023-10-29 03:19:32 26 4
gpt4 key购买 nike

我想从字符串变量中获取原始文件的大小,该变量是使用 base64 编码文件获得的。



package main

import (
"bufio"
"encoding/base64"
"io/ioutil"
"os"
)

func encodeFile(file string) string {
f, err := os.Open(file)
if err != nil {
panic(err)
}

reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
encoded := base64.StdEncoding.EncodeToString(content)
return encoded
}

func main() {
datas := encodeFile("/tmp/hello.json")
//how to get file size from datas
}

如何从datas获取文件大小?谢谢。

最佳答案

应该这样做:

func calcOrigBinaryLength(datas string) int {

l := len(datas)

// count how many trailing '=' there are (if any)
eq := 0
if l >= 2 {
if datas[l-1] == '=' {
eq++
}
if datas[l-2] == '=' {
eq++
}

l -= eq
}

// basically:
//
// eq == 0 : bits-wasted = 0
// eq == 1 : bits-wasted = 2
// eq == 2 : bits-wasted = 4

// each base64 character = 6 bits

// so orig length == (l*6 - eq*2) / 8

return (l*3 - eq) / 4
}

Playground 验证:https://play.golang.org/p/Y4v102k74V5

关于go - 如何从base64编码字符串中获取原始文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com