C# – Combine two integers to create a unique number

cintegermathstring

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 numbers,

These are my tables:

Table A 
SchoolID    ClassId
107 56644231
107 56644532
107 320110212

Table B 
SchoolID    ClassId
108 566442310
108 56644532
108 50110212

I need to export these fields to a third table combining class ID and school ID into one single field called classID. I need to be able to combine these numbers together and then be able to uncombine them to get schoolid and classid separate for update purposes. I was thinking of concatenating the strings 'schoolid + '00' + 'classid' since I know that schoolid will always be a 3 digit number but I am looking for some other way perhaps mathematical where I don't have to use string casts.

Is there a mathematical way to do this? Or is casting to string the best way to do this?

I am using C# to code the solution.

Thanks,

Best Answer

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;