Golang 结构体转字节数组(struct to []byte)

代码:

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	log "fmt"
)

type NCPTargetVersion struct {
	NCPVersion      uint16
	SoftwareVersion uint16
	HardwareVersion uint16
}

func main() {
	log.Println("create dfu file")

	// context, err := ioutil.ReadAll("./full_111.gbl")
	// if err != nil {
	// 	log.Println(err)
	// }

	var ver = &NCPTargetVersion{0x01, 0x01, 0x01}
	data, err := ver.Encode()
	if err != nil {
		log.Println(err)
		return
	}

	data = bytes_extend(data, 16)
	fmt.Println("[]byte is: ", data)
}

func (obj *NCPTargetVersion) Encode() ([]byte, error) {
	buf := new(bytes.Buffer)

	if err := binary.Write(buf, binary.BigEndian, obj); err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

func bytes_extend(data []byte, size int) []byte {
	if size > len(data) {
		var ext []byte = make([]byte, size-len(data))
		var buffer bytes.Buffer
		buffer.Write(data)
		buffer.Write(ext)
		return buffer.Bytes()
	}
	return data
}

输出:
在这里插入图片描述