Search code examples
c#uniqueunique-key

Generate a unique 2-byte integer from three integers


I have three integers:

  • First number ranges from 1-600
  • Second number ranges from 0-4
  • Third number ranges from 0-14

I need to generate a 2-byte unique integer from the above integers such that:

  • Using the same number again would result in the same number
  • Ability to get back all three numbers from the unique number
  • Unique number should be > 0 && < 32768 (2-byte)

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.


Solution

  • 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.