在PHP中使用OpenSSL随机获取负数 [英] Get Negative Numbers With OpenSSL Random In PHP

查看:105
本文介绍了在PHP中使用OpenSSL随机获取负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在弄乱一些代码,以使用PHP创建强大的伪随机数生成器.到目前为止,我有以下内容.

I'm messing around with some code to make a strong pseudo-random number generator using PHP. So far, I have the following.

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调用来确定数字是正数还是负数,但是我不确定这是否是最好的方法.

This is almost perfect for me—except that all of the numbers that I generate with openssl_random_pseudo_bytes are positive. Ideally, I'd like to generate numbers from -x to +y. I have thought about maybe adding a another PRNG call to decide if a number should be positive or negative, but I'm not sure if that's the best way to go.

推荐答案

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

You could simply add another random function, we'll use rand(0,1) this will generate 0 or 1, if it's 1 $status = 1 if it's 0 $status = -1. When we return the value we do multiplication by $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;
    }
}

这篇关于在PHP中使用OpenSSL随机获取负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆