【问题标题】:golang: convert uint32 (or any built-in type) to []byte (to be written in a file)golang:将 uint32(或任何内置类型)转换为 []byte(写入文件)
【发布时间】:2015-05-17 16:16:44
【问题描述】:

我正在尝试使用 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包吗?
  • 不一定,但是 1)我已经花了几个小时来解决这个问题,我想知道解决方案,2)我需要文件(使用十六进制编辑器分析)具有 uint32没有额外的负载,3)该解决方案也适用于 float32。我将编写写入文件的程序和读取文件的程序(相同的操作系统)。
  • 我明白了,为了方便使用,我推荐binary 包的WriteRead 方法。考虑到他们对接口的使用,他们可能会有一些开销。

标签: arrays go byte unsafe


【解决方案1】:

这是一种方法:

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 出错。

不使用 unsafe 的另一种方法是使用 encoding/binary 包:

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

【讨论】:

  • 如果系统库中存在“安全”方法,是否有理由使用不安全方法?
猜你喜欢
  • 2015-06-04
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 2014-09-01
  • 2014-02-20
  • 1970-01-01
  • 2012-01-10
  • 1970-01-01
相关资源
最近更新 更多