Generate random values in C#

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

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

9条回答
  •  悲哀的现实
    2020-12-01 06:41

    You could create a byte array, fill it with random data and then convert it to long (Int64) or ulong (UInt64).

    byte[] buffer = new byte[sizeof(Int64)];
    Random random = new Random();
    
    random.NextBytes(buffer);
    long signed = BitConverter.ToInt64(buffer, 0);
    
    random.NextBytes(buffer);
    long unsigned = BitConverter.ToUInt64(buffer, 0);
    

提交回复
热议问题