C#中文隨機數(shù)實現(xiàn)方法
更新時間:2015年06月26日 17:00:22 作者:瘋狂的流浪
這篇文章主要介紹了C#中文隨機數(shù)實現(xiàn)方法,涉及C#針對中文及隨機數(shù)的相關(guān)操作技巧,需要的朋友可以參考下
本文實例講述了C#中文隨機數(shù)實現(xiàn)方法。分享給大家供大家參考。具體如下:
/// <summary> /// 隨機中文碼 /// </summary> /// <returns></returns> private string GetRndCh() { System.Text.Encoding gb = System.Text.Encoding.Default; //獲取GB2312編碼頁(表) object[] bytes = CreateRegionCode(4); //調(diào)用函數(shù)產(chǎn)生4個隨機中文漢字編碼 string[] str = new string[4]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < 4; i++) { //根據(jù)漢字編碼的字節(jié)數(shù)組解碼出中文漢字 str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[]))); sb.Append( str[i].ToString()); } return sb.ToString (); } /// <summary> /// 產(chǎn)生隨機中文漢字編碼 /// </summary> /// <param name="strlength"></param> /// <returns></returns> private static object[] CreateRegionCode(int strlength) { //定義一個字符串?dāng)?shù)組儲存漢字編碼的組成元素 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++) { //區(qū)位碼第1位 int r1 = rnd.Next(11, 14); string str_r1 = rBase[r1].Trim(); //區(qū)位碼第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(); //區(qū)位碼第3位 rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i); //更換隨機種子 int r3 = rnd.Next(10, 16); string str_r3 = rBase[r3].Trim(); //區(qū)位碼第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(); //定義兩個字節(jié)變量存儲產(chǎn)生的隨機漢字區(qū)位碼 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16); byte byte2 = Convert.ToByte(str_r3 + str_r4, 16); //將兩個字節(jié)變量存儲在字節(jié)數(shù)組中 byte[] str_r = new byte[] { byte1, byte2 }; //將產(chǎn)生的一個漢字的字節(jié)數(shù)組放入object數(shù)組中 bytes.SetValue(str_r, i); } return bytes; }
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#中的數(shù)組作為參數(shù)傳遞所引發(fā)的問題
這篇文章主要介紹了C#中的數(shù)組作為參數(shù)傳遞所引發(fā)的問題 的相關(guān)資料,需要的朋友可以參考下2016-03-03基于C#中IDisposable與IEnumerable、IEnumerator的應(yīng)用
本篇文章小編為大家介紹,基于C#中IDisposable與IEnumerable、IEnumerator的應(yīng)用,需要的朋友參考下2013-04-04