随机数用的是msdn上的例子,不过做了下修改,随机中文因为网上找到的写法很重复,所以按照gb2312标准修改了下
随机数:
/// <summary>
/// 生成小于输入值绝对值的随机数
/// </summary>
/// <param name="NumSides"></param>
/// <returns></returns>
public static int Next(this int numSeeds)
{
numSeeds = Math.Abs(numSeeds);
if (numSeeds <= 1)
{
return 0;
}
int length = 4;
if (numSeeds <= byte.MaxValue)
{
length = 1;
}
else if (numSeeds <= short.MaxValue)
{
length = 2;
}
return Next(numSeeds, length);
}
private static int Next(int numSeeds, int length)
{
// Create a byte array to hold the random value.
byte[] buffer = new byte[length];
// Create a new instance of the RNGCryptoServiceProvider.
System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
// Fill the array with a random value.
Gen.GetBytes(buffer);
// Convert the byte to an uint value to make the modulus operation easier.
uint randomResult = 0x0;//这里用uint作为生成的随机数
for (int i = 0; i < length; i++)
{
randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
}
// Return the random number mod the number
// of sides. The possible values are zero-based
return (int)(randomResult % numSeeds);
}
随机中文:
/*
* gb2312 80
*
* 01-09区为特殊符号。
* 16-55区为一级汉字,按拼音排序。
* 56-87区为二级汉字,按部首/笔画排序。
* 10-15区及88-94区则未有编码。
*
* 所有数字都是从 1 开始
*
* 每个汉字及符号以两个字节来表示。
* 第一个字节称为“高位字节”(也称“区字节)”,upper byte
* 第二个字节称为“低位字节”(也称“位字节”)。low byte
* “高位字节”使用了0xA1-0xF7(把01-87区的区号加上0xA0),
* “低位字节”使用了0xA1-0xFE(把01-94加上 0xA0)。
* 由于一级汉字从16区起始,汉字区的“高位字节”的范围是0xB0-0xF7,
* “低位字节”的范围是0xA1-0xFE,
* 占用的码位是 72*94=6768。
* 其中有5个空位是D7FA-D7FE(55区90-94)
*/
public static string GetRandomPopularSimplifiedChinese(this int length)
{
if (length <= 0)
{
return string.Empty;
}
byte minUpper = 16;
byte maxUpper = 55;
byte rangeLow = 94;
int addParamer = 0xA0;
StringBuilder tempStr = new StringBuilder();
int tempUpper = maxUpper - minUpper + 1;
Encoding gb = Encoding.GetEncoding("gb2312");
for (int i = 0; i < length; i++)
{
int rdUpperValue = Next(tempUpper) + minUpper;
int rdLowValue;
do
{
rdLowValue = Next(rangeLow) + 1;//索引从1开始,所以94种子生成的随机数+1
}
while (rdUpperValue == maxUpper && rdLowValue >= 90);//D7FA-D7FE是空位(55区90-94)
rdUpperValue += addParamer;
rdLowValue += addParamer;
byte[] byteArray = new byte[] { (byte)rdUpperValue, (byte)rdLowValue };
tempStr.Append(gb.GetString(byteArray));
}
return tempStr.ToString();
}