我正在尝试使用 unsafe 库在 Go 中将 uint32 转换为字节数组(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)))
前两行是正确的,但随后在 copy 调用时出现运行时错误(unexpected fault address)。
下一步是调用 Write
_, err = fi.Write(a)
将 4 个字节写入文件。
我发现了具有类似主题的其他问题,但没有一个具有有效代码的问题。 我也知道 unsafe 是不安全的。
任何帮助将不胜感激。
最佳答案
避免使用 unsafe包。
使用 encoding/binary将 uint32
转换为字节 slice 的包:
h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := make([]byte, 4)
binary.LittleEndian.PutUint32(a, h)
_, err = fi.Write(a)
这个单线做同样的事情,但有额外的运行时成本:
err := binary.Write(fi, binary.LittleEndian, (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h))
以下是如何使用 unsafe 进行转换包装:
h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := (*[4]byte)(unsafe.Pointer(&h))[:]
_, err = fi.Write(a)
表达式 (*[4]byte)(unsafe.Pointer(&h))
将 uint32
指针转换为 [4]byte
指针。最后的 [:]
在 [4]byte
上创建一个 slice 。
问题中的代码将 uint32
解释为 slice header .结果 slice 无效并且 copy
错误。
关于arrays - golang : convert uint32 (or any built-in type) to []byte (to be written in a file),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29061764/