I need to generate random numbers with range for byte
, ushort
, sbyte
, short
, int
, and uint
. I am ab
The simplest approach would probably be to use two calls: one for 30 bits and one for the final two. An earlier version of this answer assumed that Random.Next()
had an inclusive upper bound of int.MaxValue
, but it turns out it's exclusive - so we can only get 30 uniform bits.
uint thirtyBits = (uint) random.Next(1 << 30);
uint twoBits = (uint) random.Next(1 << 2);
uint fullRange = (thirtyBits << 2) | twoBits;
(You could take it in two 16-bit values of course, as an alternative... or various options in-between.)
Alternatively, you could use NextBytes
to fill a 4-byte array, then use BitConverter.ToUInt32.