Combine two integers into one and decode them later

c++, integer

Solution

This is impossible.

Assuming your two identifiers can be in the range `[0, 30000]`, there are 30000 x 30000 = ~2^30 possible pairs of identifiers. However, there are only 2^16 possible 16-bit numbers. So, you can't possibly map pairs of identifiers to a 16-bit integer and expect to recover the identifiers from it.

Instead, you can use a 32-bit integer to store the combination, in which case both encoding and decoding is straightforward:

Encoding:

unsigned short Identifier1 = 12793;
unsigned short Identifier2 = 5450;
unsigned int CombinedIDs = (Identifier1 << 16) | Identifier2;

Decoding:

unsigned short Identifier1 = CombinedIDs >> 16;
unsigned short Identifier2 = CombinedIDs & 0x0000FFFF

Note that now the restriction that the identifiers be in the range [0, 30000] is not necessary - they be any unsigned short value.

EDIT Answering your comment: 4 and 12 bits are possible.

Encoding:

unsigned short Identifier1;  // 4 bits
unsigned short Identifier2;  // 12 bits
unsigned short CombinedIDs = (Identifier1 << 12) | Identifier2;

Decoding:

unsigned short Identifier1 = CombinedIDs >> 12;
unsigned short Identifier2 = CombinedIDs & 0x0FFF;

Problem

Using C++ I need to combine two distinct IDs into one 16bit integer. Then later on I need to decode this 16bit integer into the two original ID values. Example: ``` // Store two integers into one unsigned short Identifier1 = 12793; //(maximum number 30000) unsigned short Identifier1 = 5450; //(maximum number 30000) unsigned short CombinedIDs = 34283; // this is example, I don't know the code for that // Decode one integer into two // At this point I only have CombinedIDs value, I need to extract it // into the two original IDs unsigned short OriginalIdentifier1 = ...CombinedIDs.. code to get 12793 unsigned short OriginalIdentifier2 = ...CombinedIDs.. code to get 5450 ```

Original source