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

I want to get size of the original file from a string variable, which is obtained by using a base64 encode file.



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
}

how to get the file size from datas? thks.

This should do it:

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 validation: https://play.golang.org/p/Y4v102k74V5

Well, base64 encoded string has different length then original file. To get original size you can do next: 1. In function encodeFile return len(content) which is size of original file.

  1. OR you can calculate the file size using below formula:

x = (n * (3/4)) - y Where:

  1. x is the size of a file in bytes
  2. n is the len(datas)
  3. y will be 2 if Base64 ends with '==' and 1 if Base64 ends with '='.