I have three integers:
I need to generate a 2-byte unique integer from the above integers such that:
I have searched for solutions, but most solution doubles the number of bytes from 2 to 4 bytes which is not an option in my case.
First, let's convert the first range to 0-599, marked as first-1
below. Then, all you need to do is multiply the numbers together, using range maximums as multipliers:
range_of_first = 599 + 1 = 600
range_of_second = 4 + 1 = 5
range_of_third = 14 + 1 = 15
(first-1) + range_of_first * second + range_of_first * range_of_second * third
= (first-1) + 600*second + 600*5*third
= result
Maximum value you can get is 599 + 600 * 4 + 600 * 5 * 14 = 44999
This does not fit as is into a signed 2 byte integer (-32768..32767). It fits into 2 byte unsigned integer (0..65535).
If you have to fit it into a signed integer, then easiest is to do calculcation in 32 bits, then substract (44999-32768) from the result, so it will fit into range of 2-byte signed integer. Then before decoding do reverse.
And for the opposite, you need division and reminder:
first = result % range_of_first + 1 // +1 to get values 1..600
second = result / range_of_first % range_of_second
third = result / range_of_first / range_of_second // % range_of_third redundant
Above all numbers are assumed to be non-negative, and usual integer division rounding is assumed, that is just chopping off any decimals.