This should do the trick. (It's an extension method so that you can call it just as you call the normal Next
or NextDouble
methods on a Random
object).
public static Int64 NextInt64(this Random rnd)
{
var buffer = new byte[sizeof(Int64)];
rnd.NextBytes(buffer);
return BitConverter.ToInt64(buffer, 0);
}
Just replace Int64
with UInt64
everywhere if you want unsigned integers instead and all should work fine.
Note: Since no context was provided regarding security or the desired randomness of the generated numbers (in fact the OP specifically mentioned the Random
class), my example simply deals with the Random
class, which is the preferred solution when randomness (often quantified as information entropy) is not an issue. As a matter of interest, see the other answers that mention RNGCryptoServiceProvider
(the RNG provided in the System.Security
namespace), which can be used almost identically.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…