1

我需要在我的代码中生成非负随机整数。下面的示例生成整数;

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);
        }
    }

参考: http: //www.dotnetperls.com/rngcryptoserviceprovider 但它给出了正值和负值。如何只生成非负随机整数?我之前使用的是 Random.Next() ,它给了我正整数。

4

2 回答 2

3

在您的特定情况下,只需使用ToUInt32代替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);
    }
}
于 2015-04-02T07:32:44.267 回答
0

伪代码:

repeat
  temp <- RNG.nextInteger();
until temp >= 0;
return temp;
于 2015-04-01T15:54:19.177 回答