duan00529 2015-03-15 14:30 采纳率: 100%
浏览 699
已采纳

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

I'm trying to convert an uint32 to a byte array (4 bytes) in Go using the unsafe library:

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)))

The first two lines are correct, but then I get a runtime error ( unexpected fault address ) at the copy call.

The next step would be to call Write

_, err = fi.Write(a)

to write the 4 bytes into a file.

I've found other questions with a similar topic, but none with a working code. I'm also aware that unsafe is unsafe.

Any help would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • duandu2980 2015-03-15 15:07
    关注

    Here's one way to do it:

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

    Here's a breakdown of what's going on. The code

    (*[4]byte)(unsafe.Pointer(&h))
    

    converts the uint32 pointer to a [4]byte pointer. The

    [:]
    

    at the end creates a slice on the [4]byte.

    The code in the question interprets the uint32 as a slice header. The resulting slice is not valid and copy faults.

    An alternative approach that does not use unsafe is to use the encoding/binary package:

    h := (uint32)(((fh.year*100+fh.month)*100+fh.day)*100 + fh.h)
    a := make([]byte, 4)
    binary.LittleEndian.PutUint32(a, h)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值