string value of byte array – and back again to byte array

Issue

I am trying to benchmark some Decoding code. I have printed the encoding byte array, so I can hardcode it in the test file, to separate out the Encode part.

Therefore I have fmt.Println() a byte array

buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(<my struct>)
if err != nil {
    log.Fatal(err)
}
byteQuads := buf.Bytes()
buf.Reset()
fmt.Println(byteQuads) // << [77 255 129 3 1 1 7 82...]
// or
fmt.Println(string(byteQuads[:])) // << M��...

Question: How can read this hardcode into a byte array([]byte) again

b := []byte(???) // [77 255 129 3 1 1 7 82...] or M��
gob.NewDecoder(bytes.NewReader(b))

Solution

If your goal is to create a composite literal with the test data, then use the %#v format verb in fmt.Printf:

buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("var testData = %#v\n", buf.Bytes())  
// prints var testData = []byte{0x1f, 0xff, …

This code prints a line of text that you can paste directly into a Go source file.

If your goal is to reuse the encoded data over and over, then do the following:

buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(<my struct>)
if err != nil {
    log.Fatal(err)
}
b := buf.Bytes() // reuse this slice of bytes to create decoders.

⋮

dec := gob.NewDecoder(bytes.NewReader(b))
// do something with the decoder

⋮

// create another decoder on the same data.
dec = gob.NewDecoder(bytes.NewReader(b))

Answered By – Bayta Darell

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.