在PHP中使用OpenSSL Random获取负数
我正在胡乱编写一些代码,用PHP制作一个强大的伪随机数生成器。到目前为止,我有以下几点在PHP中使用OpenSSL Random获取负数,php,random,openssl,prng,Php,Random,Openssl,Prng,我正在胡乱编写一些代码,用PHP制作一个强大的伪随机数生成器。到目前为止,我有以下几点 function strongRand($bytes, $min, $max) { if(function_exists('openssl_random_pseudo_bytes')) { $strong = true; $n = 0; do{ $n = hexdec(bin2hex(openssl_random_pse
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);
}
}
函数strongRand($bytes,$min,$max)
{
if(函数_存在('openssl_随机_伪_字节'))
{
$strong=正确;
$n=0;
做{
$n=hexdec(bin2hex(openssl_随机_伪_字节($bytes,$strong));
}
而($n<$min | |$n>$max);
返回$n;
}
否则{
返回mt_兰特($min,$max);
}
}
这对我来说几乎是完美的,除了我用
openssl\u random\u pseudo\u 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;
}
}
函数strongRand($bytes,$min,$max)
{
$status=mt_rand(0,1)==1?1:-1;
if(函数_存在('openssl_随机_伪_字节'))
{
$strong=正确;
$n=0;
做{
$n=hexdec(bin2hex(openssl_随机_伪_字节($bytes,$strong));
}
而($n<$min | |$n>$max);
返回$n*$状态;
}
否则{
返回mt_rand($min,$max)*$状态;
}
}
如果需要生成从-x到+y的数字,只需生成4字节uint,并且:
$number = ($generated % ($x + $y + 1)) - $x
我故意避免使用模运算符,因为它偏向于某些数字。请参阅:
$bytes
在做什么?对于某些情况下未使用的参数,它应该是最后一个参数,但它到底做了什么/应该做什么?$bytes
是我想从openssl\u random\u pseudo\u bytes()
中获取的字节数。查看PHP文档了解更多信息。你是说strongRand(100,1,2)
对你有意义吗?字节数应该取决于范围。哦,我明白你的意思了。你说得对。字节数应取决于范围。如果你愿意的话,这只是我正在做的一个快速的“草图”。我真正关心的部分是负数的生成。