在PHP中使用OpenSSL随机获取负数


Get Negative Numbers With OpenSSL Random In PHP

我正在使用PHP编写一个强大的伪随机数生成器。到目前为止,我有以下内容:

function strongRand($bytes, $min, $max)
{
    if(function_exists('openssl_random_pseudo_bytes'))
    {
        $strong = true;
        $n = 0;
        do{
            $n = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $strong)));
        }
        while($n < $min || $n > $max);
        return $n;
    }
    else{
        return mt_rand($min, $max);
    }
}

这对我来说几乎是完美的——除了我用openssl_random_pseudo_bytes生成的所有数字都是正的。理想情况下,我希望生成从-x到+y的数字。我想过可能会添加另一个PRNG调用来决定一个数字应该是正的还是负的,但我不确定这是否是最好的方法。

您可以简单地添加另一个随机函数,我们将使用rand(0,1),这将生成0或1,如果它是1 $status = 1,如果它是0 $status = -1。当返回值时,要乘以$status:

function strongRand($bytes, $min, $max)
{
    $status = mt_rand(0,1) === 1 ? 1:-1;
    if(function_exists('openssl_random_pseudo_bytes'))
    {
        $strong = true;
        $n = 0;
        do{
            $n = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $strong)));
        }
        while($n < $min || $n > $max);
        return $n * $status;
    }
    else{
        return mt_rand($min, $max) * $status;
    }
}

如果您需要从-x到+y生成数字,您可以简单地生成4字节的单位,并且:

$number = ($generated % ($x + $y + 1)) - $x