As RNGCryptoServiceProvider is "safer" (produces high-quality random numbers) than Random() I felt for using it. Performance is not an issue. But, instead of reading the last digit, and somehow decide when to add a 0 or 1 before it.. Is there a better (more accurate) way?
byte[] data = new byte[4];
rng.GetBytes(data);
int value = BitConverter.ToInt32(data, 0);
Console.WriteLine(value);
You can use the modulo operator (%). This leads to slightly biased results, but with an 8 byte input the bias is quite small. Much smaller than the bias System.Random has.
byte[] data = new byte[8];
rng.GetBytes(data);
ulong value = BitConverter.ToUInt64(data, 0);
result = (int)(value%15+1);
Or if you want perfectly uniform numbers:
byte[] data = new byte[8];
ulong value;
do
{
rng.GetBytes(data);
value = BitConverter.ToUInt64(data, 0);
} while(value==0);
result = (int)(value%15+1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With