Golang intSlice 转换 ByteSlice


原文链接: Golang intSlice 转换 ByteSlice

binary.Write(b, binary.LittleEndian, myIntSlice)

通过 bytes.Buffer

buf := new(bytes.Buffer)
var num uint16 = 1234
err := binary.Write(buf, binary.LittleEndian, num)
if err != nil {
    fmt.Println("binary.Write failed:", err)
}
fmt.Printf("% x", buf.Bytes())
package main

import (
	"fmt"
    "strconv"
)

func main() {
	a := []int{1, 2434, 3, 4}
	fmt.Printf("%s", sByteFromSIntTwo(a, true))
}

//Converts []int to []byte
func sByteFromSIntTwo(s []int, com bool) []byte {
	b := make([]byte, 0)
	for _, test := range s {
		b = strconv.AppendInt(b, int64(test), 10)
		if com {
			b = append(b, byte(','))
		}
	}
	return b
}
`