Golang : Convert []string to []byte examples
Problem :
You need a fast way to convert a []string to []byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in []byte type.
Solutions :
Example 1:
package main
import (
"fmt"
"strings"
)
func main() {
stringSlice := []string{"hello", "bye"}
stringByte := "\x00" + strings.Join(stringSlice, "\x20\x00") // x20 = space and x00 = null
fmt.Println([]byte(stringByte))
fmt.Println(string([]byte(stringByte)))
}
Output :
[0 104 101 108 108 111 32 0 98 121 101]
hello bye
Example 2:
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
func main() {
stringSlice := []string{"hello", "bye"}
buffer := &bytes.Buffer{}
gob.NewEncoder(buffer).Encode(stringSlice)
byteSlice := buffer.Bytes()
fmt.Printf("%q\n", byteSlice)
fmt.Println("---------------------------")
backToStringSlice := []string{}
gob.NewDecoder(buffer).Decode(&backToStringSlice)
fmt.Printf("%v\n", backToStringSlice)
}
Output :
[12 255 129 2 1 2 255 130 0 1 12 0 0 14 255 130 0 2 5 104 101 108 108 111 3 98 121 101]
[hello bye]
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.9k Golang : Get uploaded file name or access uploaded files
+37.5k Golang : Convert to io.ReadSeeker type
+8.2k Golang : Scramble and unscramble text message by randomly replacing words
+15.7k Golang : How to tell if a file is compressed either gzip or zip ?
+14.9k Golang : Find out mime type from bytes in buffer
+9.7k Golang : Fix - does not implement sort.Interface (missing Len method)
+18.2k Golang : Measure http.Get() execution time
+13.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+46.2k Golang : How to convert JSON string to map and slice
+22.6k Golang : Generate MD5 checksum of a file
+21.3k Golang : Round float to precision example
+5.2k PageSpeed : Clear or flush cache on web server