2 回答
TA贡献1878条经验 获得超4个赞
例如,在小端架构上,不使用 package 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
- 2 回答
- 0 关注
- 180 浏览
添加回答
举报