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
}

将uint8的类型转换为unit32

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    u8 := []uint8{0, 1, 2, 3}
    u32LE := binary.LittleEndian.Uint32(u8)
    fmt.Println("little-endian:", u8, "to", u32LE)
    u32BE := binary.BigEndian.Uint32(u8)
    fmt.Println("big-endian:   ", u8, "to", u32BE)
}

输出:

little-endian: [0 1 2 3] to 50462976
big-endian: [0 1 2 3] to 66051

Go 二进制包函数被实现为一系列的转换。

func (littleEndian) Uint32(b []byte) uint32 {
    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}

func (bigEndian) Uint32(b []byte) uint32 {
    return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
}
`