Skip to content

Can't Generate a Random BigInteger in a Specified Range #98884

Answered by Clockwork-Muse
YBCA7 asked this question in Q&A
Discussion options

You must be logged in to vote

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).

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by danmoseley
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants