C# 生成小于Int数值绝对值的随机数

2021-07-15 03:17

阅读:649

标签:operation   ret   short   dom   buffer   create   abs   数值   i++   

C#中有两种类型的随机数生成器:

  • 伪随机数(System.Random)
  • 安全随机数(System.Security.Cryptography.RNGCryptoServiceProvider)

   关键的区别在于用于进行随机化的种子值可能不会快速且随机地变化。例如,System.Random依赖于计算机系统时钟

 

  public static class IntNumRandom
    {

        ///    
        /// 生成小于输入值绝对值的随机数   
        ///    
        ///    
        ///    
        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 )
            {
                randomResult |= ((uint)buffer[i] 1 - i) * 8));
            }
            // Return the random number mod the number   
            // of sides.  The possible values are zero-based   
            return (int)(randomResult % numSeeds);
        }


    }

 

C# 生成小于Int数值绝对值的随机数

标签:operation   ret   short   dom   buffer   create   abs   数值   i++   

原文地址:https://www.cnblogs.com/ZQWelcomeIndex/p/9523499.html


评论


亲,登录后才可以留言!