当我们想要获得一个唯一的key的时候,通常会想到GUID。这个key非常的长,虽然我们在很多情况下这并不是个问题。但是当我们需要将这个36个字符的字符串放在URL中时,会使的URL非常的丑陋。
想要缩短GUID的长度而不牺牲它的唯一性是不可能的,但是如果我们能够接受一个16位的字符串的话是可以做出这个牺牲的。
我们可以将一个标准的GUID 21726045-e8f7-4b09-abd8-4bcc926e9e28 转换成短的字符串 3c4ebc5f5f2c4edc
下面的方法会生成一个短的字符串,并且这个字符串是唯一的。重复1亿次都不会出现重复的,它也是依照GUID的唯一性来生成这个字符串的。
private string GenerateStringID()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
如果你想生成一个数字序列而不是字符串,你将会获得一个19位长的序列。下面的方法会把GUID转换为Int64的数字序列。
private long GenerateIntID()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, 0);
}
1)假设数据库是这个样子的:
2)运行以下控制台代码:
static void Main(string[] args) { //测试bigint的读取: using (SqlConnection con = new SqlConnection(@"server=.\sqlexpress;database=MyTest;integrated security=true")) { SqlCommand cmd = new SqlCommand("select top 1 number from tb_dbo", con); con.Open(); IDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleRow); dr.Read(); long n = Convert.ToInt64(dr["number"]); Console.WriteLine(n); dr.Close(); } }
3)结果如下:
当我们想要获得一个唯一的key的时候,通常会想到GUID。这个key的长度是36位,如果将这个36为的字符串存储或是用url传递的时候就会感觉非常的难看。
就算去掉-分隔符也有32位,如 EAA82B2DA9EA4E5B95330BAF9944FB35,如果转为数字序列 如将guid转为int64数字序列,长度也会有19位。
如
byte[] buffer = Guid.NewGuid().ToByteArray();
long long_guid=BitConverter.ToInt64(buffer, 0);
这样就会得到一个类似于 5472976187161141196 的19位长度的 数字序列。
如果我们将 5472976187161141196 分解为 54 72 97 61 87 161 141 196,应该可以用8个字符就可以显示,但会有一部分是不可显示的字符。
如果将这8个字符转为base64,发现只需要10-14个为就能显示完毕,将一些url用到的某些符号剔除,通常会产生12位的编码较多,10位的编码较少。
经过100万次的测试,没有发现会有重复的字符产生,不知道是否是完美的将guid 压缩为12位的方法呢?
如果你有更好的做法,可以共享出来。
附源代码
publicstaticstringUUID()
{byte[] buffer=Guid.NewGuid().ToByteArray();longlong_guid=BitConverter.ToInt64(buffer,0);string_Value=System.Math.Abs(long_guid).ToString();byte[] buf=newbyte[_Value.Length];intp=0;for(inti=0; i<_value.length>
{byteph=System.Convert.ToByte(_Value[i]);intfix=1;if((i+1)<_value.length>
{bytepl=System.Convert.ToByte(_Value[i+1]);
buf[p]=(byte)((ph<<4)+pl);
fix=2;
}else{
buf[p]=(byte)(ph);
}if((i+3)<_value.length>
{if(System.Convert.ToInt16(_Value.Substring(i,3))<256)
{
buf[p]=System.Convert.ToByte(_Value.Substring(i,3));
fix=3;
}
}
p++;
i=i+fix;
}byte[] buf2=newbyte[p];for(inti=0;i
{
buf2[i]=buf[i];
}stringcRtn=System.Convert.ToBase64String(buf2);if(cRtn==null)
{
cRtn="";
}
cRtn=cRtn.ToLower();
cRtn=cRtn.Replace("/","");
cRtn=cRtn.Replace("+","");
cRtn=cRtn.Replace("=","");if(cRtn.Length==12)
{returncRtn;
}else{returnUUID();
}
}