在C#中生成唯一的字符串和数字
当我们想要获得一个唯一的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)结果如下:
是否可以无损耗的压缩GUID为12位呢?
{
byte [] buffer = Guid.NewGuid().ToByteArray();
long long_guid = BitConverter.ToInt64(buffer, 0 );
string _Value = System.Math.Abs(long_guid).ToString();
byte [] buf = new byte [_Value.Length];
int p = 0 ;
for ( int i = 0 ; i < _Value.Length;)
{
byte ph = System.Convert.ToByte(_Value[i]);
int fix = 1 ;
if ((i + 1 ) < _Value.Length)
{
byte pl = 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 = new byte [p];
for ( int i = 0 ;i < p;i ++ )
{
buf2[i] = buf[i];
}
string cRtn = System.Convert.ToBase64String(buf2);
if (cRtn == null )
{
cRtn = "" ;
}
cRtn = cRtn.ToLower();
cRtn = cRtn.Replace( " / " , "" );
cRtn = cRtn.Replace( " + " , "" );
cRtn = cRtn.Replace( " = " , "" );
if (cRtn.Length == 12 )
{
return cRtn;
} else {
return UUID();
}