将两个或多个数字压缩为一个字节 [英] Compress two or more numbers into one byte

查看:323
本文介绍了将两个或多个数字压缩为一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这实际上是不可能的,但还是值得一问。假设我有两个小数字(每个数字从0到11)。是否有一种方法,我可以将它们压缩为一个字节,然后再将其取回。如何处理四个相似大小的数字。

I think this is not really possible but worth asking anyway. Say I have two small numbers (Each ranges from 0 to 11). Is there a way that I can compress them into one byte and get them back later. How about with four numbers of similar sizes.

我需要的是:a1 + a2 = x。我只知道x,从中得到a1,a2

第二部分:a1 + a2 + a3 + a4 = x。我只知道x,从中得到a1,a2,a3,a4

注意:我知道您不能取消添加,仅说明我的问题。

What I need is something like: a1 + a2 = x. I only know x and from that get a1, a2
For the second part: a1 + a2 + a3 + a4 = x. I only know x and from that get a1, a2, a3, a4
Note: I know you cannot unadd, just illustrating my question.

x必须为一个字节。 a1,a2,a3,a4的范围是[0,11]。

x must be one byte. a1, a2, a3, a4 range [0, 11].

推荐答案

这对于位掩码来说是微不足道的。想法是将字节分成较小的单元,并将它们专用于不同的元素。

Thats trivial with bit masks. Idea is to divide byte into smaller units and dedicate them to different elements.

对于2个数字,可能是这样的:前4位是number1,其余是number2。您将使用 number1 =(x& 0b11110000)>> 4 number2 =(x& 0b00001111)以检索值,以及 x =(number1 << 4 )|数字2 对其进行压缩。

For 2 numbers, it can be like this: first 4 bits are number1, rest are number2. You would use number1 = (x & 0b11110000) >> 4, number2 = (x & 0b00001111) to retrieve values, and x = (number1 << 4) | number2 to compress them.

这篇关于将两个或多个数字压缩为一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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