The Go language implementation transforms []string into []byte

Source: Internet
Author: User
Tags printf notification center
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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.