How can I generate random Int64 and UInt64 values using the Random
class in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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:
You could create a
byte
array, fill it with random data and then convert it tolong
(Int64
) and ulong (UInt64
).You don't say how you're going to use these random numbers...keep in mind that values returned by Random are not "cryptographically secure" and they shouldn't be used for things involving (big) secrets or (lots of) money.
Use
Random.NextBytes()
andBitConverter.ToInt64
/BitConverter.ToUInt64
.Note that using
Random.Next()
twice, shifting one value and then ORing/adding doesn't work.Random.Next()
only produces non-negative integers, i.e. it generates 31 bits, not 32, so the result of two calls only produces 62 random bits instead of the 64 bits required to cover the complete range ofInt64
/UInt64
. (Guffa's answer shows how to do it with three calls toRandom.Next()
though.)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.