Combine two integers to create a unique number

后端 未结 7 2082
北荒
北荒 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;
    

提交回复
热议问题