Implementation of Chinese Random Numbers in C
- 2021-07-03 00:48:33
- OfStack
This paper describes the implementation method of C # Chinese random number with examples. Share it for your reference. The details are as follows:
/// <summary>
/// Random Chinese code
/// </summary>
/// <returns></returns>
private string GetRndCh()
{
System.Text.Encoding gb = System.Text.Encoding.Default;
// Get GB2312 Code page (table)
object[] bytes = CreateRegionCode(4);
// Call function generation 4 Random Chinese character coding
string[] str = new string[4];
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < 4; i++)
{
// Decoding Chinese characters according to byte array encoded by Chinese characters
str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
sb.Append( str[i].ToString());
}
return sb.ToString ();
}
/// <summary>
/// Generate random Chinese character coding
/// </summary>
/// <param name="strlength"></param>
/// <returns></returns>
private static object[] CreateRegionCode(int strlength)
{
// Definition 1 A string array stores the constituent elements of Chinese character coding
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++)
{
// Area code number 1 Bit
int r1 = rnd.Next(11, 14);
string str_r1 = rBase[r1].Trim();
// Area code number 2 Bit
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();
// Area code number 3 Bit
rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
// Replace random seeds
int r3 = rnd.Next(10, 16);
string str_r3 = rBase[r3].Trim();
// Area code number 4 Bit
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();
// Define two byte variables to store the generated random Chinese character area code
byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
// Storing a two-byte variable in a byte array
byte[] str_r = new byte[] { byte1, byte2 };
// Will produce 1 A byte array of Chinese characters is put into object Array
bytes.SetValue(str_r, i);
}
return bytes;
}
I hope this article is helpful to everyone's C # programming.