博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#.net利用RNGCryptoServiceProvider产生任意范围强随机数的办法
阅读量:7128 次
发布时间:2019-06-28

本文共 1173 字,大约阅读时间需要 3 分钟。

//这样产生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对象可是很消耗资源的

原文地址:http://www.2cto.com/kf/201007/52493.html

/// <summary>

/// 生成随机数
/// </summary>
/// <param name="minVal">最小值(包含)</param>
/// <param name="maxVal">最大值(不包含)</param>
/// <returns></returns>
public static int GetRandom(int minVal, int maxVal)
{
//这样产生0 ~ 100的强随机数(不含100)
int m = maxVal - minVal;
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);
long l = BitConverter.ToInt64(rndSeries, 0);
rnd = (int)(Math.Abs(l) / _base * m);
return minVal + rnd;
}

使用:

int randomi = 0;

randomi = GetRandom(100000, 999999);

 

转载于:https://www.cnblogs.com/lcyuhe/p/7126405.html

你可能感兴趣的文章
亚马逊新专利,让无人机运送充电器为电动车充电
查看>>
HTC将Viveport推向全球,这是要“反击”Valve的节奏?
查看>>
【深度学习不是犯罪】欧盟祭出最严数据保护法:专家解读 GDPR
查看>>
浅谈SQL Server 对于内存的管理
查看>>
喜报销发布V2.4,圣诞焕新装,新增“专项费用报销”审批,集成京东商城
查看>>
陈天奇团队新研究:自动优化深度学习工作负载
查看>>
你的无人机快递来了?小心被查“水表”
查看>>
收录 Uboot 详解
查看>>
MongoDB数据库的索引操作(转)
查看>>
线程的实现
查看>>
重建日志文件
查看>>
鱼鹰软件荣获“北京广告产业发展30周年”杰出贡献单位奖
查看>>
四、oracle基本sql语句和函数详解
查看>>
中合国创杯2017年创客中国互联网+创新创业大赛复赛成功举办 20各项目入围总决赛...
查看>>
UVAoj 11324 - The Largest Clique(tarjan + dp)
查看>>
使用Matplotlib绘制正余弦函数、抛物线
查看>>
四位辉光管时钟-学长毕设
查看>>
大话RAC介质恢复---联机日志损坏
查看>>
oracle 内存分配和调优 总结
查看>>
移植最新版libmemcached到VC++的艰苦历程和经验总结(上)
查看>>