Generating Random Unsigned Integers In C# & .NET
[C#, .NET]
In the previous post, “Generating Random Values For Other Integral Types In C# & .NET”, we looked at how to generate random integers
for other unsigned integral types.
The technique of using the Next() method of the Random class, however, would not work for this case, given that it returns a signed int
, which is constrained between 2,147,483,647
and 2,147,483,647
.
This eliminates half of the range, given that an unsigned integer unit is constrained between 0
and 4,294,967,295
.
To work around this, we can use the NextInt64() method instead, and constrain that.
var randomuInt = (uint)Random.Shared.NextInt64(uint.MinValue, ((long)uint.MaxValue) + 1);
Console.WriteLine(randomuInt);
Here we are casting the value of uint.MaxValue to a long
, then adding 1 to that so that the upper bound is included.
This will print something like this:
3195959763
TLDR
We can use the Random.NextInt64
method to generate values constrained by uint.MaxValue
to generate random unsigned integral values.
The code is in my GitHub.
Happy hacking!