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
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:
Decoding:
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:
Decoding: