1

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://www.dotnetperls.com/rngcryptoserviceprovider 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.

pras007
  • 115
  • 11
  • Why can you just take the absolute value of the result: `abs(value)` http://www.w3schools.com/jsref/jsref_abs.asp – cmbarbu Apr 01 '15 at 12:57
  • I think that would create problem. Lets say the random no generator generates -2 and we will use the absolute value and use it as 2. Next it generates 2 and the random number is still 2. – pras007 Apr 01 '15 at 13:23
  • Well there are no guaranty two successive random numbers are different. What is the issue? – cmbarbu Apr 01 '15 at 13:36
  • I have to use the random integer as the Msg Id of a snmp v3 packet. So, I think as you suggest I can use "abs" method to get the positive integer. Thanks for your help. – pras007 Apr 01 '15 at 16:04

2 Answers2

3

In your specific case, just use ToUInt32 in place of ToInt32

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.ToUInt32(data, 0);
    Console.WriteLine(value);
    }
}
cmbarbu
  • 4,354
  • 25
  • 45
0

Pseudocode:

repeat
  temp <- RNG.nextInteger();
until temp >= 0;
return temp;
rossum
  • 15,344
  • 1
  • 24
  • 38
  • I did not think of that..Its a good solution. But just a question. I read in MSDN forum that it takes more time to generate a random number using RNGCryptoServiceProvider, if I skip some random numbers for a positive one, won't it affect performance? – pras007 Apr 01 '15 at 16:07
  • You are unlikely to notice the difference unless you are generating a very large number of random integers. *Always* run a timing test before you declare something too slow. A secure RNG is going to be slower than a non-secure RNG, no matter what you do. – rossum Apr 01 '15 at 18:10
  • I can't see how this would be better than taking the absolute value. Applying transformations to random numbers is a standard and adding a loop is extra complexity when simple arithmetic can do the job – cmbarbu Apr 02 '15 at 06:42