Generate random values in C#

后端 未结 9 1874
执笔经年
执笔经年 2020-12-01 06:15

How can I generate random Int64 and UInt64 values using the Random class in C#?

相关标签:
9条回答
  • 2020-12-01 06:41

    Here you go, this uses the crytpo services (not the Random class), which is (theoretically) a better RNG then the Random class. You could easily make this an extension of Random or make your own Random class where the RNGCryptoServiceProvider is a class-level object.

    using System.Security.Cryptography;
    public static Int64 NextInt64()
    {
       var bytes = new byte[sizeof(Int64)];    
       RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
       Gen.GetBytes(bytes);    
       return BitConverter.ToInt64(bytes , 0);        
    }
    
    0 讨论(0)
  • 2020-12-01 06:41

    You could create a byte array, fill it with random data and then convert it to long (Int64) or ulong (UInt64).

    byte[] buffer = new byte[sizeof(Int64)];
    Random random = new Random();
    
    random.NextBytes(buffer);
    long signed = BitConverter.ToInt64(buffer, 0);
    
    random.NextBytes(buffer);
    long unsigned = BitConverter.ToUInt64(buffer, 0);
    
    0 讨论(0)
  • 2020-12-01 06:46

    Another answer with RNGCryptoServiceProvider instead of Random. Here you can see how to remove the MSB so the result is always positive.

    public static Int64 NextInt64()
    {
        var buffer = new byte[8];
        new RNGCryptoServiceProvider().GetBytes(buffer);
        return BitConverter.ToInt64(buffer, 0) & 0x7FFFFFFFFFFFFFFF;
    }
    
    0 讨论(0)
  • 2020-12-01 06:46
    Random r=new Random();
    int j=r.next(1,23);
    Console.WriteLine(j);
    
    0 讨论(0)
  • 2020-12-01 06:52

    I always use this to get my random seed (error checking removed for brevity):

    m_randomURL = "https://www.random.org/cgi-bin/randnum?num=1&min=1&max=1000000000";
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_randomURL);
    StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
    Random rand = new Random(Convert.ToInt32(stIn.ReadToEnd()));
    

    random.org uses atmospheric noise to generate the randomness and is apparently used for lotteries and such.

    0 讨论(0)
  • 2020-12-01 06:54

    You can use bit shift to put together a 64 bit random number from 31 bit random numbers, but you have to use three 31 bit numbers to get enough bits:

    long r = rnd.Next();
    r <<= 31;
    r |= rnd.Next();
    r <<= 31;
    r |= rnd.Next();
    
    0 讨论(0)
提交回复
热议问题