The Go Language implementation transforms []string into []byte
Suppose you want to implement the conversion of the Go language string array to a byte array. The demo functions are as follows:
Func convertstringstobytes () {
stringcontent: = []string{"Notification Center", "perfect!"}
Bytecontent: = "\x00" + strings. Join (stringcontent, "\x02\x00") //x20 = space and x00 = null
FMT. Println ([]byte (bytecontent))
FMT. Println (String ([]byte (Bytecontent))
}
Full code:
Package main
Import (
"FMT"
"strings"
)
func convert () {
Stringslice: = []string{Notification Center], "Perfect!"}
Stringbyte: = "\x00" + strings. Join (Stringslice, "\x20\x00")//x20 = space and x00 = null
FMT. Println ([]byte (Stringbyte))
FMT. Println (String ([]byte (Stringbyte))
}
func main () {
convert ()
}
Operation Result:
[0 233 154 231 159 165 228 184 173 229 191 131 2 0
101 102 101 Notification Center perfect!
This is the simplest method, and there is another way to achieve the same effect. It is primarily implemented using coding mechanisms.
Package main
Import (
"bytes" "Encoding/gob" "
fmt"
)
func convert () {
Stringslice: = [] string{"Notification Center", "perfect!"}
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)
}
func main () {
convert ()
}
Welcome you!