Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang equivalent of Python's struct.pack / struct.unpack

Tags:

go

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.

like image 207
Clicquot the Dog Avatar asked Oct 21 '16 17:10

Clicquot the Dog


Video Answer


1 Answers

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

i := binary.LittleEndian.Uint64(bs)
fmt.Println(i)
like image 162
JimB Avatar answered Sep 27 '22 23:09

JimB