golang:将 uint32(或任何内置类型)转换为 []byte(写入文件)
golang: convert uint32 (or any built-in type) to []byte (to be written in a file)
我正在尝试使用 unsafe 库将 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 个字节写入文件。
我发现了具有类似主题的其他问题,但 none 具有有效代码。
我也知道 unsafe 是不安全的。
如有任何帮助,我们将不胜感激。
这是一种方法:
h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := (*[4]byte)(unsafe.Pointer(&h))[:]
这里是对正在发生的事情的细分。代码
(*[4]byte)(unsafe.Pointer(&h))
将 uint32 指针转换为 [4] 字节指针。
[:]
最后在 [4] 字节上创建一个切片。
问题中的代码将 uint32 解释为 slice header。结果切片无效并且 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)
我正在尝试使用 unsafe 库将 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 个字节写入文件。
我发现了具有类似主题的其他问题,但 none 具有有效代码。 我也知道 unsafe 是不安全的。
如有任何帮助,我们将不胜感激。
这是一种方法:
h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
a := (*[4]byte)(unsafe.Pointer(&h))[:]
这里是对正在发生的事情的细分。代码
(*[4]byte)(unsafe.Pointer(&h))
将 uint32 指针转换为 [4] 字节指针。
[:]
最后在 [4] 字节上创建一个切片。
问题中的代码将 uint32 解释为 slice header。结果切片无效并且 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)