猿问

将 []byte 数组转换为 uintptr

如何将以下字节数组转换为 uintptr?(不是 uint32 或 uint64):

arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}


长风秋雁
浏览 332回答 2
2回答

MYYA

假设它uintptr是 64 位,并且您需要大端编码,即使不深入研究标准库的binary包,您也可以很容易地构造正确的值。package mainimport "fmt"func main() {&nbsp; &nbsp; arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}&nbsp; &nbsp; var r uintptr&nbsp; &nbsp; for _, b := range arr {&nbsp; &nbsp; &nbsp; &nbsp; r = (r << 8) | uintptr(b)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("%x", r)}daccd97424f4如果您使用的是 64 位 int 版本的 go(而不是例如在 go 操场上),则此代码会输出。

幕布斯6054654

您可以使用encoding.binary包:arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}for i := 0; i < 8 - len(arr); i++ {&nbsp; &nbsp; arr = append([]byte{0x0, 0x0}, arr...) // for not to get index out of range}ptr := binary.BigEndian.Uint64(arr)fmt.Printf("0x%x\n", uintptr(ptr))https://play.golang.org/p/QFUVlIFdLZL
随时随地看视频慕课网APP

相关分类

Go
我要回答