doule6314 2016-10-21 17:23
浏览 831
已采纳

相当于Python的struct.pack / struct.unpack的Golang

In Python, using the struct module, I can do something like this to get a packed representation of a value as a string:

import struct
print struct.pack('L', 64)
"@\x00\x00\x00\x00\x00\x00\x00"
struct.unpack('L', '@\x00\x00\x00\x00\x00\x00\x00')
(64,)

I'd like to do something similar in Go, except I'm a little unclear on how to do so. I know I can do something like this:

import (
    "encoding/binary"
    "fmt"
)

bs := make([]byte, 8)
binary.PutUvarint(bs, uint64(64))
fmt.Printf("%s", bs)
"@"

But that's very different and probably not what I want.

  • 写回答

2条回答 默认 最新

  • doubiaokai4998 2016-10-21 17:28
    关注

    Yes, "encoding/binary" is what you want, you just don't want the variable length format.

    https://play.golang.org/p/e81LuPO_JR

    bs := make([]byte, 8)
    binary.LittleEndian.PutUint64(bs, uint64(64))
    fmt.Printf("%#v
    ", bs)
    
    i := binary.LittleEndian.Uint64(bs)
    fmt.Println(i)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制