Can't Generate a Random BigInteger in a Specified Range #98884
-
It seems that the code below has no problem. However, it usually returns a number out of range. using System;
using System.Numerics;
using System.Security.Cryptography;
private BigInteger EncryptedRandBigInt(BigInteger min, BigInteger max, RNGCryptoServiceProvider r)
{
BigInteger range = max - min;
byte[] buffer = new byte[(int)range.BitLength /8 + 1];
do { r.GetBytes(buffer); } while (new BigInteger(buffer) > range);
return new BigInteger(buffer) + min;
} |
Beta Was this translation helpful? Give feedback.
Answered by
Clockwork-Muse
Feb 24, 2024
Replies: 1 comment
-
Because %50 of the time the generated bytes will result in a negative number, due to the high bit of the last byte being set. You have to explicitly set the high bit to zero to force it to be positive. See also this explanatory SO answer (Although use of some more modern APIs may allow you to cut down on the allocations). |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
danmoseley
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because %50 of the time the generated bytes will result in a negative number, due to the high bit of the last byte being set. You have to explicitly set the high bit to zero to force it to be positive.
See also this explanatory SO answer (Although use of some more modern APIs may allow you to cut down on the allocations).