在 Go 中将结构体内容复制到 uint64

我想将结构的值复制到 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)

}


慕田峪7331174
浏览 181回答 2
2回答

UYOU

例如,在小端架构上,不使用 package unsafe,package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "unsafe")type T struct {&nbsp; &nbsp; id [7]byte&nbsp; &nbsp; no uint8}func Uint64LEFromT(t T) uint64 {&nbsp; &nbsp; return uint64(t.id[0]) | uint64(t.id[1])<<8 | uint64(t.id[2])<<16 | uint64(t.id[3])<<24 |&nbsp; &nbsp; &nbsp; &nbsp; 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) {&nbsp; &nbsp; t.id[0] = byte(v)&nbsp; &nbsp; t.id[1] = byte(v >> 8)&nbsp; &nbsp; t.id[2] = byte(v >> 16)&nbsp; &nbsp; t.id[3] = byte(v >> 24)&nbsp; &nbsp; t.id[4] = byte(v >> 32)&nbsp; &nbsp; t.id[5] = byte(v >> 40)&nbsp; &nbsp; t.id[6] = byte(v >> 48)&nbsp; &nbsp; t.no = byte(v >> 56)}func main() {&nbsp; &nbsp; t1, t2 := T{[7]byte{'A', 'B', 'C', 'D', 'E', 'F', 'G'}, 7}, T{}&nbsp; &nbsp; var u1, u2 uint64&nbsp; &nbsp; //TODO: copy t1's content into u1 (both id and no)&nbsp; &nbsp; u1 = *((*uint64)(unsafe.Pointer(&t1)))&nbsp; &nbsp; fmt.Printf("t1 to u1 (unsafe): t1 %X u1 %X\n", t1, u1)&nbsp; &nbsp; //DONE:&nbsp; &nbsp; u2 = Uint64LEFromT(t1)&nbsp; &nbsp; fmt.Printf("t1 to u2 (safe):&nbsp; &nbsp;t1 %X u2 %X\n", t1, u2)&nbsp; &nbsp; Uint64LEToT(&t2, u2)&nbsp; &nbsp; fmt.Printf("u2 to t2 (safe):&nbsp; &nbsp;t2 %X u2 %X\n", t2, u2)}输出:t1 to u1 (unsafe): t1 {41424344454647 7} u1 747464544434241t1 to u2 (safe):&nbsp; &nbsp;t1 {41424344454647 7} u2 747464544434241u2 to t2 (safe):&nbsp; &nbsp;t2 {41424344454647 7} u2 747464544434241
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go