How to pack/unpack binary data

1,032 views
Skip to first unread message

Francesco Bochicchio

unread,
Jun 5, 2010, 1:06:51 PM6/5/10
to golang-nuts
Hi all,

I'm reading a little bit about go. Nice language, BTW, although not
all syntactic choices suit my taste (but I guess this is true for each
pair (programmer, language)). My favorite features are goroutines and
interfaces.

But let's go to the question : I'm browsing the standard library, but
I haven't find how I should go if I need to pack a set of values in a
specific binary structure, or viceversa. The binary structure could
be a packet received from the network or a block of bytes read from a
file. In other words, how do I do something equivalent to this piece
of C code

unsigned pack( int f1, float f2, char buffer[8] )
{
unsigned idx = 0;
memcpy( buffer+idx, &f1, sizeof(int) ); idx += sizeof(int);
memcpy( buffer+idx, &f2, sizeof(float) ); idx += sizeof(float);

return idx;
}

or the specular function to extract an int32 and a float from a block
of 8 bytes.

I just started today reading about go, so probably I'm missing
something.

Ciao
------
FB

Rob 'Commander' Pike

unread,
Jun 5, 2010, 1:14:44 PM6/5/10
to Francesco Bochicchio, golang-nuts
Two ways:

1) Use package encoding/binary.
2) Do byte I/O to assemble values. math.Float32frombits will help with the floating values.

Go is type safe so the C trick of just reading into some address will not work.

-rob

Francesco Bochicchio

unread,
Jun 5, 2010, 1:45:00 PM6/5/10
to golang-nuts
Thanks, encoding/binay was what I was looking for. The C example was
only to explain the result I wanted.

Ciao
------
FB
Reply all
Reply to author
Forward
0 new messages