views:

3159

answers:

8

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

+14  A: 

Use Random.NextBytes() and BitConverter.ToInt64 / BitConverter.ToUInt64.

// Assume rng refers to an instance of System.Random
byte[] bytes = new byte[8];
rng.NextBytes(bytes);
long int64 = BitConverter.ToInt64(bytes, 0);
ulong uint64 = BitConverter.ToUInt64(bytes, 0);

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 of Int64/UInt64. (Guffa's answer shows how to do it with three calls to Random.Next() though.)

Jon Skeet
Oh, good catch (comment) - I'm deleting mine, as the BitConverter etc is already well covered...
Marc Gravell
Okay - I put that in my answer rather than just a comment so that it would be more visible. I'm going to leave it in now anyway as a warning for the future (as otherwise it's an obvious alternative).
Jon Skeet
Due to the fact that majority of lcm PRNG are less random in the low order bits, generating 2 numbers and joining them together may introduce subtle biases...
Mitch Wheat
Downvoters: Any reasons to give?
Jon Skeet
+25  A: 

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 be used almost identically.

Noldorin
+1 for giving the OP what they asked for as well as mentioning the limitations of using Random and offering an alternative if the limitations of Random are too restrictive for the intended use.
JeffH
Note that this approach also returns negative numbers and Int64.MaxValue, while System.Random.Next() is constrained to positive numbers including 0 but without Int32.MaxValue.
Christoph Rüegg
@Christoph: Yeah, well observed. You could however modify my method quite easily to only produce positive values by ignoring the MSB (most significant bit) of the buffer.
Noldorin
+1  A: 

You could create a byte array, fill it with random data and then convert it to long (Int64) and 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);
Samuel
+2  A: 

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.

Dan
-1 for not mentioning the .Net Crypto RNG. http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx
Samuel
Why is that relevant? Dan alludes to the fact that a PC can't generate a cryptographically secure random number. The RNGCryptoServiceProvider class doesn't fix that.
sipwiz
No, he said the Random class can't do it, he said nothing about computers not being able to.
Samuel
And RNGCryptoServiceProvider generates cryptographically secure random numbers and satisfies that condition of his answer.
Samuel
he wasn't wrong, just not complete. doesn't deserve -1, just maybe not +1 :)
Lucas
... and he makes a good point many people miss.
Lucas
John Von Neumann: "Anyone who considers arithmetic methods of producing random digits is, of course, in a state of sin."
sipwiz
While he makes a good point, if he had just spent a minute more he would have found RNGCryptoServiceProvider and his answer would be much more valuable.
Samuel
Hope you gave -1 to Jon Skeet and Noldorin as well then. They didn't mention the wekaness of the Random class at all. Beats me why you get 12+ votes for detailing a simple Int64 conversion but then that's prob just sour grapes on my behalf :-(.
sipwiz
Why detail the various alternatives to "Random" when it isn't clear whether they're even needed or not? Not to mention, the question was specifically about "using the Random class".
Dan
The asker did not mention he required a secure random number, but it is nice you pointed out that the Random class does not produce secure numbers, but you really should mention an alternative instead of leaving a dead end.
Samuel
+2  A: 

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.

sipwiz
+2  A: 

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();
Guffa
+3  A: 

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);        
}
Muad'Dib
This is definitely worthwhile noting, although judging by the question the OP doesn't seem to care too greatly about the randomness of the generated numbers. Also it's important to realise that RNGCryptoServiceProvider is *much* slower than Random (though performance may or may not matter here).
Noldorin
A: 

Random r=new Random(); int j=r.next(1,23); Console.WriteLine(j);

the random class is used to randomly select the values.random class give a well environment to the user to do so