高效地将压缩值写入流中。

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

Efficiently write compressed values to stream

问题

目前,我正在尝试从现有的C代码中翻译一些压缩算法。

对我来说,编码和解码似乎并不困难。更多的是关于序列化到流(无论是文件还是套接字)以及从流中反序列化的问题。

输入是12位,压缩输出是7位。但是将数据写入流中总是涉及写入整个8位。

因此,由于每个值始终剩余1位,这是否意味着我需要缓冲7个字节才能写入8个值?这将产生以下字节(其中所有的1都属于第一个值,所有的2都属于第二个值,依此类推):

11111112
22222233
33333444
44445555
55566666
66777777
78888888

实际的编解码器或使用的编程语言并不重要(实际上:编解码器是G.711,编程语言是Golang)。所以也许go标签不合适。

对此有什么线索吗?

英文:

Currently, I'm trying to translate some compression algorithm from existing C code.

Encoding and decoding doesn't appear difficult to me. It's more about the serialization to and from a stream (be it a file or a socket).

The input is 12 bit and the compressed output is 7 bits. But writing something to a stream always involves writing entire 8 bits.

So as there is always 1 bit remaining for each value, does that mean I would have to buffer 7 bytes just to be able to write 8 values? Which would give the following bytes (whereas all 1s belong to the first value, all 2's to the second one, etc.)

11111112
22222233
33333444
44445555
55566666
66777777
78888888

The real codec or the language being used both don't really matter (actually: the codec is G.711 and the language is Golang). So maybe the go-Tag is inappropriate.

Any clue on this?

答案1

得分: 0

使用二进制移位运算符将每次加载七个位到位缓冲器中,并且每当位缓冲器有八个位时,输出它。最后,如果有任何剩余的位,输出一个包含缓冲器中内容的最后一个字节。

所以类似这样(不了解Go语言,但这应该接近):

bits = 0
bitbuf = 0
... 一些循环 ...
    ... 生成你的七个位 ...
    bitbuf |= sevenbits << bits
    bits += 7
    if bits >= 8 {
        output(bitbuf & 0xff)
        bitbuf >>= 8;
        bits -= 8;
    }
...
if bits > 0 {
    output(bitbuf)
}
英文:

Use binary shift operators to load seven bits at a time into a bit buffer, and whenever the bit buffer has eight bits, output that. At the end, if there are any bits leftover, output a final byte with what's in the buffer.

So something like (don't know Go, but this should be close):

bits = 0
bitbuf = 0
... some loop ...
    ...make your seven bits ...
    bitbuf |= sevenbits &lt;&lt; bits
    bits += 7
    if bits &gt;= 8 {
        output(bitbuf &amp; 0xff)
        bitbuf &gt;&gt;= 8;
        bits -= 8;
    }
...
if bits &gt; 0 {
    output(bitbuf)
}

huangapple
  • 本文由 发表于 2015年7月15日 23:23:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/31434554.html
匿名

发表评论

匿名网友

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

确定