如何将3个整数编码为2个整数?

发布于 2025-02-13 22:18:26 字数 344 浏览 1 评论 0原文

我有三个整数(x1,x2,x3)全部在[0,255]中。我需要将它们编码为两个整数(ab),以便我可以确定性地将它们解码。约束是新整数的大小必须很小。 因此,我可以做a = 256*x1+x2,但这使得axi大得多。

有什么方法可以编码整数以使结果数保持很小? 我没有定义什么是小,我想尽可能小。

一个类似的问题是将这些3数字编码为1。同样,新整数需要尽可能小。有什么办法吗?

I have three integers (x1,x2,x3) all in [0,255]. I need to encode them into two integers (a, and b) such that I can deterministically decode them back. The constraint is that the size of the new integers needs to be small.
So I can do a=256*x1+x2, but this makes a much larger than xi.

Any way to encode integers such that the resulting numbers stay small?
I am not defining what small is, as I want as small as possible.

A similar problem is to encode these 3 numbers into just 1. Again the new integer needs to be as small as possible. Any way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆光下的微笑 2025-02-20 22:18:28

欢迎来到信息理论 / PIGONHOLE原理。如果您想编码x不同的值,则需要有足够的位来区分x不同的事物。在您的情况下,有256 = 2 ** 8可能性(使用**用于指示),x1x2 < /code>和x3。因此,总共有2 ** 24组合的可能性。因此,您需要2 ** 24组合。因此,24位。

可以使用范围0-4095中的12位数字来实现您的第一个编码。并且您的编码可以如下完成(其中是剩余的操作,//是整数部门,因为它们在Python3中):

a = (x1%16) * 256 + x2
b = (x1//16) * 256 + x3

使用:编码

x1 = (a//256) + (b//256) * 16
x2 = a%256
x3 = b%256

: 1数字再次需要2 ** 24可能性,因此数字需要在范围内0..16777215。这次编码是:

c = x1 + 256*x2 + 65536*x3

通过解码,

x1 = c%256
x2 = (c//256)%256
x3 = c//65536

您可以实现各种其他编码/解码。但是,它们的数字范围比这是无法实现的。

Welcome to information theory / the pigeonhole principle. If you wish to encode x different values, you need to have enough bits to distinguish between x different things. In your case there are 256 = 2**8 possibilities (using ** for exponentiation) for each of x1, x2, and x3. Therefore in total there are 2**24 possibilities for the combination. Therefore you will need 2**24 combinations. So 24 bits.

Your first encoding can be achieved using 12 bit numbers in the range 0-4095. And your encoding can be done as follows (where % is the remainder operation and // is integer division, as they are in Python3):

a = (x1%16) * 256 + x2
b = (x1//16) * 256 + x3

with a decoding of:

x1 = (a//256) + (b//256) * 16
x2 = a%256
x3 = b%256

Encoding into 1 number again needs 2**24 possibilities, so that number needs to be in the range 0..16777215. And the encoding this time is:

c = x1 + 256*x2 + 65536*x3

with a decoding of

x1 = c%256
x2 = (c//256)%256
x3 = c//65536

There are various other encodings/decodings that you can achieve. But they can't be achieved with smaller ranges of numbers than that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文