C#/ASP.NET生成6位随机数,做邀请码时可用
在C#中,生成随机数的方法很多,最简单的是Random ,但是不能保证重复,下面共享一个6位随机数代码public string GetInvitationCode()
{
//自定义进制,长度为34。0和1与o和l容易混淆,不包含在进制中。
char[] r = new char[] {'Q', 'w', 'E', '8', 'a', 'S', '2', 'd', 'Z', 'x', '9', 'c', '7', 'p', 'O', '5', 'i', 'K', '3', 'm', 'j', 'U', 'f', 'r', '4', 'V', 'y', 'L', 't', 'N', '6', 'b', 'g', 'H'};
char[] b = new char[] { 'q', 'W', 'e', '5', 'A', 's', '3', 'D', 'z', 'X', '8', 'C', '2', 'P', 'o', '4', 'I', 'k', '9', 'M', 'J', 'u', 'F', 'R', '6', 'v', 'Y', 'T', 'n', '7', 'B', 'G', 'h'};
char[] buf = new char;
int s = 6;//生成六位的邀请码
int binLen = r.Length;
int charPos = 33;
//以当前的毫秒数作为标准
int id = DateTime.Now.Millisecond;
while ( id / binLen > 0 )
{
int k = (int) (id % binLen);
buf [--charPos] = r;
id /= binLen;
}
buf [--charPos] = r[ ( int ) ( id % binLen ) ];
String str = new String ( buf , charPos , ( 33 - charPos ) );
//长度不够6位时自动随机补全
if ( str.Length < s )
{
StringBuilder sb = new StringBuilder ( );
Random rd = new Random ( );
for ( int i = 1; i <= s - str.Length; i ++)
{
sb.Append ( b );
}
str += sb.ToString();
}
return str.ToUpper();
}
111
页:
[1]