tags:

views:

93

answers:

3

As we all know a byte range is 0 to 255
i have two byte, I want to create another number that is reversible but with minimum length that combine these two number and create a new one, the simplest solution is

a = b1 * 1000 + b2

reverse would be

b1 = a / 1000
b2 = a % 1000

the length of above solution varying 0 to 6 length, i want a formula with FIXED and minimum length

+1  A: 

Well the simplest general purpose solution here would be

a = b1 * 256 + b2;

aka

a = (b1 << 8) | b2;

Then to get them back (assuming you've got unsigned bytes available):

b1 = (a >> 8) & 0xff;
b2 = a & 0xff;

That will produce a 2-byte value for all inputs, unless you deem the results of b1=0, b2=* to be one byte (as every value is less than 256). You could potentially interleave things, such that the low four bits of each input byte ends up in the low eight bits of the output, so that you'd end up with a value of less than 256 for (b1 < 16, b2 < 16). Frankly it's easiest to always just consider it as a 2-byte value, using the above shifting.

Using 2 bytes is clearly a minimum, and it's easily achievable.

If that's not what you're looking for, please give more information.

EDIT: I've been assuming you're looking for a fixed binary length. If you want a fixed decimal length, use falagar's solution.

Jon Skeet
+1  A: 

If you mean a fixed-length number when expressed in decimal, you can use:

a = 100,000 + b1 * 256 + b2

That will give you a number from 100,000 to 165,535 inclusive.

To reverse the operation:

b1 = (a - 100,000) / 256
b2 = (a - 100,000) % 256
paxdiablo
@paxdiablo: falagar's solution gives a smaller fixed size.
Jon Skeet
Yes, I must be getting senile :-)
paxdiablo
+3  A: 

Encode:

x = b1 * 256 + b2;
x = x + 10000;

Decode:

x = x - 10000;
b1 = x >> 8;
b2 = x & 255;

Encoded result always has length 5 (10000 through 75535 inclusive). And since there are 65536 different pairs (b1, b2) you can't encode them into numbers of length < 5 (because there are at most 10000 such numbers).

falagar
D'Oh. My solution but with one less digit. I don't know _how_ that could have escaped me. +1.
paxdiablo
Your solution is great, Is there any smaller one ? for example 4 digit with some kind of complex formula ?
Ehsan
@Ehsan: How could there be 4 digits when there are 65536 different input values?
Jon Skeet
Ooops !! Yes you are right that would be imposible
Ehsan
Why are you adding 1000? Why not just prefix shorter numbers with '0'?
Nick Johnson