c#.net利用RNGCryptoServiceProvider产生任意范围(int32)强随机数的办法
c#.net利用RNGCryptoServiceProvider产生任意范围强随机数的办法
//这样产生0 ~ 100的强随机数(含100)
int max = 100;
int rnd = int.MinValue;
decimal _base = (decimal)long.MaxValue;
byte[] rndSeries = new byte[8];
System.Security.Cryptography.RNGCryptoServiceProvider rng
= new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(rndSeries);
//不含100需去掉+1
rnd = (int)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base * (max+1));
//这个rnd就是你要的随机数,
//但是要注意别扔到循环里去,实例化RNG对象可是很消耗资源的
int max = 100;
int rnd = int.MinValue;
decimal _base = (decimal)long.MaxValue;
byte[] rndSeries = new byte[8];
System.Security.Cryptography.RNGCryptoServiceProvider rng
= new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(rndSeries);
//不含100需去掉+1
rnd = (int)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base * (max+1));
//这个rnd就是你要的随机数,
//但是要注意别扔到循环里去,实例化RNG对象可是很消耗资源的