mercredi 1 avril 2015

How to generate non-negative random numbers(integer) using RNGCryptoServiceProvider C#

I need to generate non-negative random integers in my code. The example below generates integers;



using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// Buffer storage.
byte[] data = new byte[4];

// Ten iterations.
for (int i = 0; i < 10; i++)
{
// Fill buffer.
rng.GetBytes(data);

// Convert to int 32.
int value = BitConverter.ToInt32(data, 0);
Console.WriteLine(value);
}
}


Ref: http://ift.tt/1GgaMYq But it gives both positive and negative values. How do I generate only non-negative random integers? I was earlier using Random.Next() which was giving me positive integers.





Aucun commentaire:

Enregistrer un commentaire