PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 18, 2022

[FIXED] How to encode 3 integers into 2 integers?

 July 18, 2022     algorithm, integer, mapping, math     No comments   

Issue

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?


Solution

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.



Answered By - btilly
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing