Generate random uint

前端 未结 3 658
孤独总比滥情好
孤独总比滥情好 2021-02-18 14:14

I need to generate random numbers with range for byte, ushort, sbyte, short, int, and uint. I am ab

3条回答
  •  时光说笑
    2021-02-18 15:12

    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.

提交回复
热议问题