码迷,mamicode.com
首页 > Windows程序 > 详细

【C#】绝对随机数

时间:2017-10-30 11:29:33      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:instance   mat   with   result   private   security   tco   size   make   

System.Security.Cryptography.RNGCryptoServiceProvider

        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);
        }

--

            for (int i = 0; i < 20; i++)
            {
                byte[] randomBytes = new byte[8];
                System.Security.Cryptography.RNGCryptoServiceProvider rngServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();
                rngServiceProvider.GetBytes(randomBytes);
                int result = BitConverter.ToInt32(randomBytes, 0);
                result = System.Math.Abs(result);  //求绝对值
                Console.WriteLine(result);
            }

 

【C#】绝对随机数

标签:instance   mat   with   result   private   security   tco   size   make   

原文地址:http://www.cnblogs.com/oiliu/p/7753096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!