C# – Generate Random UInt

c++randomuint

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?

Best Answer

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.

Related Question