douhandie6615 2014-04-14 12:04
浏览 126
已采纳

如何在Go中将位保存到文件

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条回答 默认 最新

  • dongxindu8753 2014-04-14 12:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献