Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress two or more numbers into one byte

Tags:

algorithm

math

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.

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 must be one byte. a1, a2, a3, a4 range [0, 11].

like image 941
Dave Avatar asked Aug 17 '10 04:08

Dave


2 Answers

Let's say it in general: suppose you want to mix N numbers a1, a2, ... aN, a1 ranging from 0..k1-1, a2 from 0..k2-1, ... and aN from 0 .. kN-1.

Then, the encoded number is:

encoded = a1 + k1*a2 + k1*k2*a3 + ... k1*k2*..*k(N-1)*aN

The decoding is then more tricky, stepwise:

rest = encoded
a1 = rest mod k1
rest = rest div k1

a2 = rest mod k2
rest = rest div k2

...

a(N-1) = rest mod k(N-1)
rest = rest div k(N-1)

aN = rest # rest is already < kN
like image 111
Tomas Avatar answered Oct 15 '22 04:10

Tomas


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

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.

like image 42
Daniel Kluev Avatar answered Oct 15 '22 03:10

Daniel Kluev