在.net FCL中random没有生成long类型的随机数,不过random可以生成0-1的随机数,这就可以帮助实现random Long.
如下为一简单实现(.net 3.5):
Random NextLong
1
static
class
Common
2 {
3 public static long NextLong( this Random random,long minValue,long maxValue)
4 {
5 if (minValue > maxValue)
6 {
7 throw new ArgumentException( " minValue is great than maxValue " , " minValue " );
8 }
9 long num = maxValue - minValue;
10 return minValue + ( long ) (random.NextDouble() * num);
11 }
12 }
2 {
3 public static long NextLong( this Random random,long minValue,long maxValue)
4 {
5 if (minValue > maxValue)
6 {
7 throw new ArgumentException( " minValue is great than maxValue " , " minValue " );
8 }
9 long num = maxValue - minValue;
10 return minValue + ( long ) (random.NextDouble() * num);
11 }
12 }
使用如下:
1
Random random
=
new
Random();
2 random.NextLong(MinSize, MaxSize);
2 random.NextLong(MinSize, MaxSize);
由于random.NextDouble() 是根据Int32来生成的,其个数为Int32.Max个。如果上述NextLong连续调用maxValue-minValue+1次,在maxValue-minValue+1 > Int32.Max时,未必能生成所有可能近视分布均匀的随机数据。
现 更新如下:
代码
public static long NextLong
(
this Random random
,
long min
,
long max
)
{
byte[] minArr = BitConverter . GetBytes ( min );
int hMin = BitConverter . ToInt32 ( minArr , 4 );
int lMin = BitConverter . ToInt32 ( new byte[] { minArr[ 0 ] , minArr[ 1 ] , minArr[ 2 ] , minArr[ 3 ] } , 0 );
byte[] maxArr = BitConverter . GetBytes ( max );
int hMax = BitConverter . ToInt32 ( maxArr , 4 );
int lMax = BitConverter . ToInt32 ( new byte[] { maxArr[ 0 ] , maxArr[ 1 ] , maxArr[ 2 ] , maxArr[ 3 ] } , 0 );
if ( random == null )
{
random = new Random ();
}
int h = random . Next ( hMin , hMax );
int l = 0 ;
if ( h == hMin )
{
l = random . Next ( Math . Min ( lMin , lMax ), Math . Max ( lMin , lMax ));
}
else
{
l = random . Next ( 0 , Int32 . MaxValue );
}
byte[] lArr = BitConverter . GetBytes ( l );
byte[] hArr = BitConverter . GetBytes ( h );
byte[] result = new byte[ 8 ] ;
for ( int i = 0 ; i < lArr . Length ; i ++)
{
result[i] = lArr[i] ;
result[i + 4 ] = hArr[i] ;
}
return BitConverter . ToInt64 ( result , 0 );
}
{
byte[] minArr = BitConverter . GetBytes ( min );
int hMin = BitConverter . ToInt32 ( minArr , 4 );
int lMin = BitConverter . ToInt32 ( new byte[] { minArr[ 0 ] , minArr[ 1 ] , minArr[ 2 ] , minArr[ 3 ] } , 0 );
byte[] maxArr = BitConverter . GetBytes ( max );
int hMax = BitConverter . ToInt32 ( maxArr , 4 );
int lMax = BitConverter . ToInt32 ( new byte[] { maxArr[ 0 ] , maxArr[ 1 ] , maxArr[ 2 ] , maxArr[ 3 ] } , 0 );
if ( random == null )
{
random = new Random ();
}
int h = random . Next ( hMin , hMax );
int l = 0 ;
if ( h == hMin )
{
l = random . Next ( Math . Min ( lMin , lMax ), Math . Max ( lMin , lMax ));
}
else
{
l = random . Next ( 0 , Int32 . MaxValue );
}
byte[] lArr = BitConverter . GetBytes ( l );
byte[] hArr = BitConverter . GetBytes ( h );
byte[] result = new byte[ 8 ] ;
for ( int i = 0 ; i < lArr . Length ; i ++)
{
result[i] = lArr[i] ;
result[i + 4 ] = hArr[i] ;
}
return BitConverter . ToInt64 ( result , 0 );
}