How to save bits to a file in Go

huangapple go评论66阅读模式
英文:

How to save bits to a file in Go

问题

我想在Go语言中对一些数据进行序列化,并且我需要编写单个位(特别是用于Huffman编码)。最直观的方法是每次取八个位,并将第一个位左移7位,第二个位左移6位,依此类推。

我想知道是否有更符合惯用方式的方法来实现这个,可能是标准库中的一个函数。我已经查看了encoding/gob,但它似乎没有提供我所希望的控制,例如写入一个包含4个布尔值的切片(我原以为对应于位),输出了24个字节。我猜想它可能有一些数字来表示切片的起始位置、布尔值的下一个位置等。

有没有好的方法来实现这个?

英文:

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?

答案1

得分: 1

encoding/gob是Go语言值的二进制编码。它与位操作没有任何关系。它的主要目的是为了在网络连接等场景下提供高性能的解决方案,用于传输Go数据结构(特别是rpc包)。

Go语言中切片的内部表示是一个结构体,包含一个指向数组(适当类型的数组)的指针,以及两个整数,一个用于表示切片的长度(即切片中元素的数量),一个用于表示切片底层数组的容量(即为数组分配的内存大小)。

我认为标准库中没有支持你想要实现的功能。所以我认为你需要自己编写实现,就像你自己建议的那样。

也许你可以将相关的代码放在一个单独的包中并分享出来,Go语言是一门年轻的语言,需要像这样的实现,我认为。

很抱歉我不能提供更多帮助。

英文:

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 length (i.e. the number of elements in the slice) and capacity (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.

huangapple
  • 本文由 发表于 2014年4月14日 20:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/23059653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定