使用Go语言中的encoding/binary包进行字节序转换

huangapple go评论73阅读模式
英文:

byte endian convert by using encoding/binary in Go

问题

我收到了运行时错误消息Write T1 binary.Read: invalid type main.T1

package main

import (
	"encoding/binary"
	"net"
)

type T1 struct {
	f1 [5]byte
	f2 int
}

func main() {
	conn, _ := net.Dial("tcp", ":12345")
	l1 := T1{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
	binary.Write(conn, binary.BigEndian, &l1)
}

我希望使用自动转换字节序的功能,我该如何做呢?
顺便问一下,有没有更高效的方法?

英文:

I got the runtime error message Write T1 binary.Read: invalid type main.T1

package main

import (
	"encoding/binary"
	"net"
)

type T1 struct {
	f1 [5]byte
	f2 int
}

func main() {
	conn, _ := net.Dial("tcp", ":12345")
	l1 := T1{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
	binary.Write(conn, binary.BigEndian, &l1)
}

I wish to use the endian auto convert function, how could I do?
By the way, is there more efficient way?

答案1

得分: 9

使用导出的固定大小字段。例如,

package main

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

type T struct {
    F1 [5]byte
    F2 int32
}

func main() {
    var t1, t2 T
    t1 = T{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
    fmt.Println("t1:", t1)
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, &t1)
    if err != nil {
        fmt.Println(err)
    }
    err = binary.Read(buf, binary.BigEndian, &t2)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("t2:", t2)
}

输出:

t1: {[97 98 99 100 101] 1234}
t2: {[97 98 99 100 101] 1234}
英文:

Use exported fixed size fields. For example,

package main

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

type T struct {
	F1 [5]byte
	F2 int32
}

func main() {
	var t1, t2 T
	t1 = T{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
	fmt.Println("t1:", t1)
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, &t1)
	if err != nil {
		fmt.Println(err)
	}
	err = binary.Read(buf, binary.BigEndian, &t2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("t2:", t2)
}

Output:

t1: {[97 98 99 100 101] 1234}
t2: {[97 98 99 100 101] 1234}

答案2

得分: 2

引用来自binary/encoding文档的_exactomundo_的话:

> 固定大小的值可以是固定大小的算术类型(int8,uint8,int16,float32,complex64,...)或仅包含固定大小值的数组或结构体。

因此:

type T1 struct {
    f1 [5]uint8
    f2 int32
}

在这里起作用。

英文:

Quoting exactomundo from binary/encoding docs:

> A fixed-size value is either a fixed-size arithmetic type (int8, uint8, int16, float32, complex64, ...) or an array or struct containing only fixed-size values.

And therefore:

type T1 struct {
    f1 [5]uint8
    f2 int32
}

works here.

huangapple
  • 本文由 发表于 2011年11月8日 00:36:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/8039552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定