golang:将uint32(或任何内置类型)转换为[] byte(写入文件)

Mik*_*dez 10 arrays byte unsafe go

我正在尝试使用不安全的库将uint32转换为Go中的字节数组(4个字节):

h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := make([]byte, unsafe.Sizeof(h))
copy(a, *(*[]byte)(unsafe.Pointer(&h)))
Run Code Online (Sandbox Code Playgroud)

前两行是正确的,但后来我在复制调用时遇到运行时错误(意外故障地址).

下一步是调用Write

_, err = fi.Write(a)
Run Code Online (Sandbox Code Playgroud)

将4个字节写入文件.

我发现了类似主题的其他问题,但没有一个有工作代码.我也知道不安全是不安全的.

任何帮助将不胜感激.

Cer*_*món 13

这是一种方法:

h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := (*[4]byte)(unsafe.Pointer(&h))[:]
Run Code Online (Sandbox Code Playgroud)

这是对正在发生的事情的细分.代码

(*[4]byte)(unsafe.Pointer(&h))
Run Code Online (Sandbox Code Playgroud)

将uint32指针转换为[4]字节指针.该

[:]
Run Code Online (Sandbox Code Playgroud)

最后在[4]字节上创建一个切片.

问题中的代码将uint32解释为切片标头.生成的切片无效且出现copy故障.

不使用不安全的替代方法是使用encoding/binary包:

h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := make([]byte, 4)
binary.LittleEndian.PutUint32(a, h)
Run Code Online (Sandbox Code Playgroud)

  • 如果“安全”方法存在系统库,是否有理由使用不安全方法? (2认同)