Create the smallest unique number of two bytes

As we all know, the range of bytes is from 0 to 255.
I have two bytes, I want to create another number that is reversible, but with a minimum length, which combine these two numbers and create a new, simplest solution

a = b1 * 1000 + b2

the opposite will be

b1 = a / 1000
b2 = a% 1000

the length of the above solution, varying from 0 to 6, I need a formula with FIXED and minimum length

+3
source share
3 answers

Encode:

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

Decode:

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

5 (10000 75535 ). 65536 (b1, b2), < 5 ( 10000).

+4

,

a = b1 * 256 + b2;

a = (b1 << 8) | b2;

, ( ):

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

2- , , b1=0, b2=* ( 256). , , 256 (b1 < 16, b2 < 16). , 2- , .

2 , , , .

, , .

EDIT: , . , falagar.

+1

, , :

a = 100,000 + b1 * 256 + b2

100 000 165 535 .

:

b1 = (a - 100,000) / 256
b2 = (a - 100,000) % 256
+1
source

Source: https://habr.com/ru/post/1760283/


All Articles