3

How in C# can I generate a pseudorandom uint with some maximum? (A minimum is not needed.) There seem to be plenty of questions asking for a fully random one, but nothing with an upper limit.

Clarification: This upper limit may be greater than int.MaxValue, so just casting Random.Next(int) does not help.

AlphaModder
  • 3,266
  • 2
  • 28
  • 44

4 Answers4

7

You can simply generate a number between Int32.MinValue and In32.MaxValue and shift up by half your range:

var random = new Random();
int number = random.Next(Int32.MinValue, Int32.MaxValue);
uint uintNumber = (uint)(number + (uint)Int32.MaxValue);
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
3

Idea is to generate random 4-byte array then it doesn't matter whether you convert into Int32 or UInt32 it's up to you:

var buffer = new byte[sizeof(uint)];
new Random().NextBytes(buffer);
uint result = BitConverter.ToUInt32(buffer, 0);

result = (result % (max - min)) + min;
Andriy Horen
  • 2,861
  • 4
  • 18
  • 38
0

this trick would do it

    static void Main(string[] args)
    {
        uint MaxValue = 5555;
        uint value;
        var rnd = new Random();
        var bytes = new byte[4];

        do
        {
            rnd.NextBytes(bytes);
            value = BitConverter.ToUInt32(bytes, 0);
        } while (value > MaxValue);

    }
Fredou
  • 19,848
  • 10
  • 58
  • 113
-3

First, create a new object of the random class:

Random r = new Random();

Then, get your numbers out of it:

int myRandomNumber = r.Next(myMaximum + 1);

So r.Next(10) would return a number 1-9 inclusive.

Finally, cast it into uint: myRandomUInt = (UInt)myRandomNumber;

xXliolauXx
  • 1,273
  • 1
  • 11
  • 25