Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two integers to create a unique number

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,

like image 302
jangeador Avatar asked Nov 22 '10 17:11

jangeador


People also ask

How do I find a unique number?

The number will be unique if it is positive integer and there are no repeated digits in the number. In other words, a number is said to be unique if and only if the digits are not duplicate. For example, 20, 56, 9863, 145, etc. are the unique numbers while 33, 121, 900, 1010, etc.

How do you concatenate numbers?

This means that you can no longer perform any math operations on them. To combine numbers, use the CONCATENATE or CONCAT, TEXT or TEXTJOIN functions, and the ampersand (&) operator. Notes: In Excel 2016, Excel Mobile, and Excel for the web, CONCATENATE has been replaced with the CONCAT function.

What is unique number in maths?

Zero is a unique number. there are only two numbers that remain the same when you square them, 0 and 1.

How do you combine two numbers in Java?

To concatenate a String and some integer values, you need to use the + operator. Let's say the following is the string. String str = "Demo Text"; Now, we will concatenate integer values.


1 Answers

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;
like image 152
userx Avatar answered Sep 21 '22 19:09

userx