Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random uint

Tags:

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?

like image 625
jaqui Avatar asked Jun 13 '13 05:06

jaqui


People also ask

What does .next do in C#?

Next() method in C# is used to return a non-negative random integer.

How do you generate random numbers in C sharp?

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);


1 Answers

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.

like image 69
Jon Skeet Avatar answered Sep 17 '22 15:09

Jon Skeet