I want to encode a string in Go using ASCII encoding like my C# function below:
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
I know how to do it using the below function:
import (
"encoding/ascii85"
"fmt"
)
func main() {
dst := make([]byte, 25, 25)
dst2 := make([]byte, 25, 25)
ascii85.Encode(dst, []byte("Hello, playground"))
fmt.Println(dst)
ascii85.Decode(dst2, dst, false)
fmt.Println(string(dst2))
}
Currently it is hard coded to a length of 25. How could I adjust the length based on the size of the string?
CodePudding user response:
ascii85.MaxEncodedLen()
returns the maximum number of output bytes for the given number of input bytes. You may use this upper estimation.
The actual number of bytes used / written is returned ascii85.Encode()
. If you passed a bigger slice to Encode()
, you must use this to slice the destination slice, bytes beyond this are "garbage".
Same goes for ascii85.Decode()
: it returns the number of written bytes, you must use that to slice the destination if you passed a bigger slice.
Also since decoding may fail (invalid input), you should also check the returned error.
Also since it's not guaranteed the given input will result in an output that is a multiple of the used 32-bit blocks, pass flush=true
to consume the given input slice (and not wait for more input).
The final, corrected code:
s := []byte("Hello, playground")
maxlen := ascii85.MaxEncodedLen(len(s))
dst := make([]byte, maxlen)
n := ascii85.Encode(dst, s)
dst = dst[:n]
fmt.Println(string(dst))
dst2 := make([]byte, maxlen)
n, _, err := ascii85.Decode(dst2, dst, true)
if err != nil {
panic(err)
}
dst2 = dst2[:n]
fmt.Println(string(dst2))
Which outputs (try it on the Go Playground):
87cURD_*#MCghU