go - 如何在 golang 中将 uintptr 转换为 []byte?

标签 go

我不知道怎么办。 它不使用 []byte(uintptr(0)) 进行编译。

请给我举个例子。

最佳答案

这取决于您机器的架构(32 位或 64 位)以及您希望如何对其进行编码(小端或大端)。无论哪种方式,encoding/binary是你的答案:

var u uintptr = 42
size := unsafe.Sizeof(u)
b := make([]byte, size)
switch size {
case 4:
    binary.LittleEndian.PutUint32(b, uint32(u))
case 8:
    binary.LittleEndian.PutUint64(b, uint64(u))
default:
    panic(fmt.Sprintf("unknown uintptr size: %v", size))
}

Playground :http://play.golang.org/p/tIocqy-rAJ .

关于go - 如何在 golang 中将 uintptr 转换为 []byte?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223562/

相关文章:

multithreading - Chdir 和Setuid 以及Setgid 线程安全吗?

database - 无法使用 go_client PUT GridDB 容器

json unmarshal 不工作但解码确实

go - Go Imaginary Literals 的最佳用途是什么?

string - 如何替换Go中字符串中特定索引处的字母?

linux - Golang for-select 炸毁 CPU

go - 使用本地包构建 docker 时出现错误 'import path does not begin with hostname'

go - 为什么运行“go test”仅在我的main_test.go文件中运行测试?

arrays - $ concatArrays仅支持数组,不支持对象

go - 我可以遍历仅是 [] 结构的结构吗?