在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位呢?
當我們想要獲得一個唯一的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位的方法呢? 如果你有更好的做法,可以共享出來。 附源代碼 public static string UUID()
{
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();
}
複制代碼 }
轉載于:https://www.cnblogs.com/anan/archive/2012/03/26/2418324.html