Combine two integers to create a unique number

后端 未结 7 2059
北荒
北荒 2020-12-10 02:05

Good Morning,

I was looking for a way to combine two integers to create a unique number, I have two tables that I need to combine into a third table with unique numb

相关标签:
7条回答
  • 2020-12-10 02:12

    Similar to Magnus Hoff, but I would recommend using a binary friendly approach instead of a base 10 approach.

    combinedid = (classid << 8) + schoolid;
    

    And then, later:

    classid = combinedid >> 8;
    schoolid = combinedid & 0xFF;
    

    I think this is a little more straight forward from a programming standpoint (making it clear that your school ID is 1 byte (0-255), the class ID is 3 bytes).

    You could also easily do this with a bigint (Long / Int64), making two int32's a single int64 safely:

    combinedid = ((long)classid << 32) + schoolid;
    
    0 讨论(0)
  • 2020-12-10 02:19

    Use ((a + b)(a + b + 1) * 0.5) + b Reference http://en.wikipedia.org/wiki/Pairing_function

    0 讨论(0)
  • 2020-12-10 02:20
    combinedid = classid*1000 + schoolid
    

    And then, later:

    classid = combinedid / 1000 // Integer division
    schoolid = combinedid % 1000
    
    0 讨论(0)
  • 2020-12-10 02:31

    If SchoolID is always a 3 digit number multiply ClassId by 1000 then add SchoolID.

    Your number might "overflow" though., and given the ones you have if they are 32-bit they will.

    0 讨论(0)
  • 2020-12-10 02:31

    You indicate that you are working with a table. This leads me to believe that you are working within a database.

    So I have to ask, why not store them in separate columns and make them simple foreign keys? Why create the ambiguity of trying to concatenate or transform the numbers with a math equation?

    If you use another table, you can use an auto increment field and the combination of the three fields (in the order you designate) will give you a unique ID.

    |-------------------
    | My_combine_table
    |-------------------
    | id   | auto_inc 
    |-------------------
    | SchoolID | ...
    | SchoolID2 | ...
    
    0 讨论(0)
  • 2020-12-10 02:31

    This SO thread has detailed various other mathematical approaches, some are just better. But for your case I suspect if those are hardly good ideas. I would say you should save the two ids in a 3rd table which has its own unique id (primary key) column.

    0 讨论(0)
提交回复
热议问题