本文實例講述了C#中文隨機數實現方法。分享給大家供大家參考。具體如下:
/// <summary>/// 隨機中文碼/// </summary>/// <returns></returns>private string GetRndCh(){ System.Text.Encoding gb = System.Text.Encoding.Default; //獲取GB2312編碼頁(表) object[] bytes = CreateRegionCode(4); //調用函數產生4個隨機中文漢字編碼 string[] str = new string[4]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < 4; i++) { //根據漢字編碼的字節數組解碼出中文漢字 str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[]))); sb.Append( str[i].ToString()); } return sb.ToString (); } /// <summary> /// 產生隨機中文漢字編碼 /// </summary> /// <param name="strlength"></param> /// <returns></returns> private static object[] CreateRegionCode(int strlength) { //定義一個字符串數組儲存漢字編碼的組成元素 string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; Random rnd = new Random(); object[] bytes = new object[strlength]; for (int i = 0; i < strlength; i++) { //區位碼第1位 int r1 = rnd.Next(11, 14); string str_r1 = rBase[r1].Trim(); //區位碼第2位 rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i); int r2; if (r1 == 13) { r2 = rnd.Next(0, 7); } else { r2 = rnd.Next(0, 16); } string str_r2 = rBase[r2].Trim(); //區位碼第3位 rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i); //更換隨機種子 int r3 = rnd.Next(10, 16); string str_r3 = rBase[r3].Trim(); //區位碼第4位 rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i); int r4; if (r3 == 10) { r4 = rnd.Next(1, 16); } else if (r3 == 15) { r4 = rnd.Next(0, 15); } else { r4 = rnd.Next(0, 16); } string str_r4 = rBase[r4].Trim(); //定義兩個字節變量存儲產生的隨機漢字區位碼 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16); byte byte2 = Convert.ToByte(str_r3 + str_r4, 16); //將兩個字節變量存儲在字節數組中 byte[] str_r = new byte[] { byte1, byte2 }; //將產生的一個漢字的字節數組放入object數組中 bytes.SetValue(str_r, i); } return bytes;}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答