Generate random values in C#

后端 未结 9 1900
执笔经年
执笔经年 2020-12-01 06:15

How can I generate random Int64 and UInt64 values using the Random class in C#?

9条回答
  •  Happy的楠姐
    2020-12-01 07:03

    Use Random.NextBytes() and BitConverter.ToInt64 / BitConverter.ToUInt64.

    // Assume rng refers to an instance of System.Random
    byte[] bytes = new byte[8];
    rng.NextBytes(bytes);
    long int64 = BitConverter.ToInt64(bytes, 0);
    ulong uint64 = BitConverter.ToUInt64(bytes, 0);
    

    Note that using Random.Next() twice, shifting one value and then ORing/adding doesn't work. Random.Next() only produces non-negative integers, i.e. it generates 31 bits, not 32, so the result of two calls only produces 62 random bits instead of the 64 bits required to cover the complete range of Int64/UInt64. (Guffa's answer shows how to do it with three calls to Random.Next() though.)

提交回复
热议问题