doufen9815 2018-07-12 05:02
浏览 650

在GoLang中将int64的Slice转换为字节数组,反之亦然

I need to convert a slice of int64 to a byte array in golang. I am successfully able to do so for a single int64

var p int64 = -3984171602573983744
fmt.Println(p)
cn := make([]byte, 8)
binary.LittleEndian.PutUint64(cn, uint64(p))
fmt.Println(cn)

How can I implement it for a slice of int64?

To be more precise, I am trying to call a function in a library which writes to a DB, and that function takes a byte array as a param. I have a slice of int64 which I need to convert to a byte array and vice versa. Is this possible?

  • 写回答

2条回答 默认 最新

  • duan5991518 2018-07-12 06:37
    关注

    For each of the int64's loop and store it like binary.LittleEndian.PutUint64(cn[x:], yourUint64), where x becomes 0,8,16...as you loop. Your cn should be big enough to take all the data (it'll be some multiple of 8). When you want to read, do the reverse: x1 := binary.LittleEndian.Uint64(cn[n:n+8]), where n becomes 0, 1, 2..

    See https://play.golang.org/p/YVQOAG8-Xlm for a simpler muxing-demuxing example.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据