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

相当于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.

图片转代码服务由CSDN问答提供 功能建议

在Python中,使用 struct 模块,我可以执行以下操作来获取 值的压缩表示形式:字符串

  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,)
   \  n 
 

我想在Go中做类似的事情,除了我不清楚如何去做。 我知道我可以做这样的事情:

  import(
“ encoding / binary” 
“ fmt” 
)
 
bs:= make([ 字节8)
binary.PutUvarint(bs,uint64(64))
fmt.Printf(“%s”,bs)
“ @” 
   
 
 

但这是非常不同的,可能不是我想要的。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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)
    
    打赏 评论
  • dpbf62565 2017-05-26 17:08

    There are a couple interesting solutions.

    1st is gist that's simple to follow and its limitations are clear:

    https://gist.github.com/cloveryume/9a59e8d77f5836f11720#file-golang_struct_packed-go

    2nd is a package that tries to the job of packing:

    https://github.com/lunixbochs/struc

    打赏 评论

相关推荐 更多相似问题