I need to generate random numbers with range for byte
, ushort
, sbyte
, short
, int
, and uint
. I am able to generate for all those types using the Random method in C# (e.g. values.Add((int)(random.Next(int.MinValue + 3, int.MaxValue - 2)));
) except for uint since Random.Next
accepts up to int values only.
Is there an easy way to generate random uint
?
Next() method in C# is used to return a non-negative random integer.
To generate random numbers in C#, use the Next(minValue, MaxValue) method. The parameters are used to set the minimum and maximum values. Next(100,200);
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
.
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