问题描述
早安,
我一直在寻找一种方式来两个整数相结合,创造一个唯一的编号,我有我需要组合成第三个表的两个表具有独特的数字,
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,
这是我的表:
Table A
SchoolID ClassId
107 56644231
107 56644532
107 320110212
Table B
SchoolID ClassId
108 566442310
108 56644532
108 50110212
我需要这些字段导出到第三个表结合的类ID和学校的ID到一个叫的classID单一领域。我需要能够将这些数字结合在一起,然后才能uncombine他们得到schoolid和CLASSID分开进行更新的目的。我在想串联串的'schoolid +'00'+'的classid
,但因为我知道,schoolid将永远是一个3位数的号码,我在找一些其他的方式也许是数学,我没有使用字符串转换。
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?
我使用C#的解决方案代码。
I am using C# to code the solution.
谢谢,
推荐答案
要马格努斯·霍夫相似,但我会建议使用二进制友好的方式,而不是基地10的方法。
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;
我觉得这是一个小更直接的,从编程的角度来看(这就很清楚,你的学生证是1字节(0-255),类ID为3个字节)。
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).
您也可以很容易地用BIGINT(长/ Int64的)做到这一点,做两个INT32的单一的Int64安全:
You could also easily do this with a bigint (Long / Int64), making two int32's a single int64 safely:
combinedid = ((long)classid << 32) + schoolid;
这篇关于结合两个整数创建一个唯一的编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!