How to assign string to bytes array

后端 未结 9 878
盖世英雄少女心
盖世英雄少女心 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:22

    For converting from a string to a byte slice, string -> []byte:

    []byte(str)
    

    For converting an array to a slice, [20]byte -> []byte:

    arr[:]
    

    For copying a string to an array, string -> [20]byte:

    copy(arr[:], str)
    

    Same as above, but explicitly converting the string to a slice first:

    copy(arr[:], []byte(str))
    

    • The built-in copy function only copies to a slice, from a slice.
    • Arrays are "the underlying data", while slices are "a viewport into underlying data".
    • Using [:] makes an array qualify as a slice.
    • A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable).
    • If the string is too long, copy will only copy the part of the string that fits.

    This code:

    var arr [20]byte
    copy(arr[:], "abc")
    fmt.Printf("array: %v (%T)\n", arr, arr)
    

    ...gives the following output:

    array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
    

    I also made it available at the Go Playground

    0 讨论(0)
  • 2020-12-12 09:22

    Piece of cake:

    arr := []byte("That's all folks!!")
    
    0 讨论(0)
  • 2020-12-12 09:25

    Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16([]byte, uint16).

    func byte16PutString(s string) [16]byte {
        var a [16]byte
        if len(s) > 16 {
            copy(a[:], s)
        } else {
            copy(a[16-len(s):], s)
        }
        return a
    }
    
    var b [16]byte
    b = byte16PutString("abc")
    fmt.Printf("%v\n", b)
    

    Output:

    [0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
    

    Notice how I wanted padding on the left, not the right.

    http://play.golang.org/p/7tNumnJaiN

    0 讨论(0)
提交回复
热议问题