0

I want to get a random uint in C#, am I doing correctly?

Random ran;
a[i] = (uint)ran.Next(int.MaxValue); //random only gets to maxInt
if (ran.Next(2) == 1)
    a[i] = (uint)(a[i] | (1 << 31));

Another thing that confuses me is that I can't write it as (uint)(a[i] | (uint)(1 << 31)).

Theraot
  • 31,890
  • 5
  • 57
  • 86
cloudyFan
  • 2,296
  • 3
  • 16
  • 14

2 Answers2

4

Did you even try running your code? It should throw NullReferenceException right away, because you don't initialize your ran random generator.

And you can simply get random int from within int.MinValue and int.MaxValue and cast it to uint in unchecked context:

Random ran = new Random();
a[i] = (uint)ran.Next(int.MinValue, int.MaxValue);
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • You should be using the overload of `Random.Next` that takes no parameters, unless you're explicitly trying here to exclude `int.MaxValue` as a possible result. It's an *exclusive* upper bound when using the overloads that take parameters. – Damien_The_Unbeliever Jan 10 '14 at 07:12
  • @Damien_The_Unbeliever The one without parameters returns only positive numbers, so it would not be enough to fill `uint`. – MarcinJuraszek Jan 10 '14 at 07:17
  • I've now posted an alternative that can return all possible `uint` values. – Damien_The_Unbeliever Jan 10 '14 at 07:24
1

To obtain a random uint for the entire possible range, we shouldn't be using Random.Next(int,int) because the second parameter is an exclusive upper bound.

(i.e. it will never generate the binary value 01111111111111111111111111111111).

I thought Random.Next() would be suitable, but as MarcinJuraszek points out, that doesn't produce half the range required.

So if you do want the full range of possible results, I guess it's time for:

var ran = new Random();
var buffer = new byte[4];
ran.GetBytes(buffer);
a[i] = BitConverter.ToUint32(buffer,0);
Amarnath Balasubramanian
  • 9,300
  • 8
  • 34
  • 62
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448