在struct和byte数组之间进行转换 [英] Go conversion between struct and byte array
本文介绍了在struct和byte数组之间进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Go中编写了一个客户端 - 服务器应用程序。我想在Go中执行类似C的类型转换。
I am writing a client - server application in Go. I want to perform C-like type casting in Go.
例如。在Go
type packet struct {
opcode uint16
data [1024]byte
}
var pkt1 packet
...
n, raddr, err := conn.ReadFromUDP(pkt1) // error here
此外,我想要执行C类memcpy(),这将允许我直接映射网络字节流接收到一个结构。
Also I want to perform C-like memcpy(), which will allow me to directly map the network byte stream received to a struct.
例如与上面接收的pkt1
e.g. with above received pkt1
type file_info struct {
file_size uint32 // 4 bytes
file_name [1020]byte
}
var file file_info
if (pkt1.opcode == WRITE) {
memcpy(&file, pkt1.data, 1024)
}
推荐答案
unsafe.Pointer
是,很好,不安全,你实际上不需要它在这里。请改用 encoding / binary
包:
unsafe.Pointer
is, well, unsafe, and you don't actually need it here. Use encoding/binary
package instead:
// Create a struct and write it.
t := T{A: 0xEEFFEEFF, B: 3.14}
buf := &bytes.Buffer{}
err := binary.Write(buf, binary.BigEndian, t)
if err != nil {
panic(err)
}
fmt.Println(buf.Bytes())
// Read into an empty struct.
t = T{}
err = binary.Read(buf, binary.BigEndian, &t)
if err != nil {
panic(err)
}
fmt.Printf("%x %f", t.A, t.B)
a href =http://play.golang.org/p/jcn6ldeAEX>游乐场
Playground
如您所见,它处理大小和字节顺序整齐。
As you can see, it handles sizes and endianness quite neatly.
这篇关于在struct和byte数组之间进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文