I want to serialise some data in Go and I have to write the individual bits. (Specifically for Huffman encoding). What is the best way to do this? The most obvious way would be to just take eight bits at a time and shift the first one 7 places to the left, six with the next one and so on.
I was wondering whether or not there was a more idiomatic way to do this, possibly a function in the standard library. I've had a look at encoding/gob, however it does not seem to offer the control I wish, for example writing a slice of 4 booleans (which I would have thought corresponded to bits) outputed 24 bytes. I'm guessing it has numbers which signify slice start, boolean next etc.
Is there a good way to do this?
encoding/gob is a binary encoding for go values. It has nothing to do what so ever with bit operations. It's main purpose is to provide a performant solution for transfering go datastructures over network connections etc (especially for the rpc package).
golang's internal representation of slices is a struct containing a pointer to an array (of appropriate type), and two ints, one for len
gth (i.e. the number of elements in the slice) and cap
acity (i.e. the ammount of memory allocated for the array.
I don't think there is support in the standard library for what you want to accomplish. So I think you need to write your own implementation, as you suggested yourself.
Maybe you can put the relevant code in a separate package and share it, go is a young language and needs implemetions like this, I think.
Sorry I couldn't be of more help.