zoukankan      html  css  js  c++  java
  • 随机long(Random long/NextLong)

     在.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     }

     使用如下:

    1 Random random = new Random();
    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);
    }
  • 相关阅读:
    错误:Authentication with old password no longer supported, use 4.1 style passwords.
    百度有钱 邀请码
    [datatables杂记] sAjaxSource 数据源 Search 后 fnInitComplete 不执行。
    uploadify onComplete 不执行?
    VS 2013 简体中文 专业版 下载地址。
    C# 导出图片到Word (通过XML实现)
    使用OutLook发送一封带附件的邮件
    WebBrower使用 Http 代理访问网页
    .net SMTP 发送邮件
    C# 汉字转拼音 方法(汉字的发音不过400多种(不算声调))
  • 原文地址:https://www.cnblogs.com/zzj8704/p/1757420.html
Copyright © 2011-2022 走看看