How to assign string to bytes array

后端 未结 9 911
盖世英雄少女心
盖世英雄少女心 2020-12-12 08:59

I want to assign string to bytes array:

var arr [20]byte
str := \"abc\"
for k, v := range []byte(str) {
  arr[k] = byte(v)
}

Have another m

9条回答
  •  星月不相逢
    2020-12-12 09:10

    Go, convert a string to a bytes slice

    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.

    package main
    
    func main() {
    
        var s string
    
        //...
    
        b := []byte(s)
    
        //...
    }
    

    which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:

    WriteFile func(filename string, data []byte, perm os.FileMode) error
    

    Another example

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
    
        stringSlice := []string{"hello", "world"}
    
        stringByte := strings.Join(stringSlice, " ")
    
        // Byte array value
        fmt.Println([]byte(stringByte))
    
        // Corresponding string value
        fmt.Println(string([]byte(stringByte)))
    }
    

    Output:

    [104 101 108 108 111 32 119 111 114 108 100] hello world

    Please check the link playground

提交回复
热议问题