我想将strcuture的值复制到uint64中,没有不安全的正确方法是什么?
package main
import "fmt"
type T struct {
id [7]byte
no uint8
}
func main() {
t1 := T{[7]byte{'A', 'B', 'C', 'D', 'E', 'F', 'G'}, 7}
var u uint64
//TODO: copy t1's content into u (both id and no)
//u = *((*uint64)(unsafe.Pointer(&t1)))
fmt.Println(t1, u)
}
答案 0 :(得分:2)
您尝试过类型广告吗?
u = uint64(t1.no)
啊,好的。你尝试过binary.Write / binary.Read吗?
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type T struct {
id [7]byte
no uint8
}
func main() {
t1 := T{[7]byte{'A', 'B', 'C', 'D', 'E', 'F', 'G'}, 7}
var u uint64
var b bytes.Buffer
binary.Write(&b, binary.LittleEndian, &t1)
binary.Read(&b, binary.LittleEndian, &u)
fmt.Println(t1, u)
}
但是,请注意二进制包使用反射包,反映包使用不安全的包。
答案 1 :(得分:2)
例如,在little-endian体系结构上,不使用包unsafe
,
package main
import (
"fmt"
"unsafe"
)
type T struct {
id [7]byte
no uint8
}
func Uint64LEFromT(t T) uint64 {
return uint64(t.id[0]) | uint64(t.id[1])<<8 | uint64(t.id[2])<<16 | uint64(t.id[3])<<24 |
uint64(t.id[4])<<32 | uint64(t.id[5])<<40 | uint64(t.id[6])<<48 | uint64(t.no)<<56
}
func Uint64LEToT(t *T, v uint64) {
t.id[0] = byte(v)
t.id[1] = byte(v >> 8)
t.id[2] = byte(v >> 16)
t.id[3] = byte(v >> 24)
t.id[4] = byte(v >> 32)
t.id[5] = byte(v >> 40)
t.id[6] = byte(v >> 48)
t.no = byte(v >> 56)
}
func main() {
t1, t2 := T{[7]byte{'A', 'B', 'C', 'D', 'E', 'F', 'G'}, 7}, T{}
var u1, u2 uint64
//TODO: copy t1's content into u1 (both id and no)
u1 = *((*uint64)(unsafe.Pointer(&t1)))
fmt.Printf("t1 to u1 (unsafe): t1 %X u1 %X\n", t1, u1)
//DONE:
u2 = Uint64LEFromT(t1)
fmt.Printf("t1 to u2 (safe): t1 %X u2 %X\n", t1, u2)
Uint64LEToT(&t2, u2)
fmt.Printf("u2 to t2 (safe): t2 %X u2 %X\n", t2, u2)
}
输出:
t1 to u1 (unsafe): t1 {41424344454647 7} u1 747464544434241
t1 to u2 (safe): t1 {41424344454647 7} u2 747464544434241
u2 to t2 (safe): t2 {41424344454647 7} u2 747464544434241