Generate random values in C#

后端 未结 9 1909
执笔经年
执笔经年 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: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;
    }
    

提交回复
热议问题