如何将整数编码为其他整数 [英] How to encode integers into other integers

查看:148
本文介绍了如何将整数编码为其他整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 Store 2 4-的后续行动1位数的位数,我想知道是否有一个概括,你可以将n个x位数存储到m位数。例如,您可以将5个8位数存储到3个15位数中。或者将2个8位数字转换为1个16位数字,或将3个16位数字转换为2个32位数字。想知道对于执行此操作的过程的编码和解码的实现是什么,或者如果不可能。

As a follow up to Store 2 4-bit numbers in 1 8 bit number, I am wondering if there is a generalization to it where you can store n x-bit numbers into m y-bit numbers. For example, maybe you can store 5 8 bit numbers into 3 15-bit numbers. Or maybe 2 8-bit numbers into 1 16 bit number, or 3 16 bit numbers into 2 32 bit numbers. Wondering what the implementation would be for encoding and decoding for a procedure that did this, or if it's not possible.

类似于:

function encode(i, s1, n, s2) {
  // i = array of input bytes
  // s1 = size of input bytes
  // n = number of output bytes
  // s2 = size of output bytes
}

function decode(i, s1, n, s2) {

}


推荐答案

一般案例是流式传输,无论一切都变得多么错位,它都能正常工作。像往常一样,它通过降低效率来支付一般性。它基本上可以通过将输入放入缓冲区直到至少一次输出大块然后提取所有输出来完成,所以这样的事情:

The general case is "streaming", which works no matter how badly misaligned everything gets. As usual, it pays for generality by being less efficient. It basically works by dropping input into a buffer until at least once chunk of output can be extracted from it and then extracting all the output, so something like this:

buffer = 0
bbits = 0
mask = (1 << outSize) - 1
while more input:
    while bbits < outSize:
        buffer |= in() << bbits
        bbits += inSize
    while bbits >= outSize:
        out(buffer & mask)
        buffer >>= outSize
        bbits -= outSize
if bbits != 0:
    out(buffer & mask)

编码和解码在概念上是相同的,但是交换了大小。当专用于特定大小的输入和输出块时,其中一个内部循环将不是循环。也可以使用其他打包顺序,在低位之前输出一大块输入的高位,无论你喜欢哪种。

Encoding and decoding is conceptually the same, but with the sizes swapped. When specialized to specific sizes of input and output chunk, one of the inner loops will not be a loop. An other packing order could be used too, outputting the high bits of a chunk of input before the low bits, whichever you like.

缓冲区的大小必须是至少 outSize - 1 + inSize ,以便在从缓冲区输出后保留最大位数后适应读取输入。

The size of the buffer must be at least outSize - 1 + inSize, to accommodate reading input after the maximum number of bits is left over after outputting from the buffer.

在此过程中甚至可以更改尺寸。

The sizes can even be changed during the procedure.

这篇关于如何将整数编码为其他整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆