Get Negative Numbers With OpenSSL Random In PHP -


i'm messing around code make strong pseudo-random number generator using php. far, have 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);     } } 

this perfect me—except of numbers generate openssl_random_pseudo_bytes positive. ideally, i'd generate numbers -x +y. have thought maybe adding prng call decide if number should positive or negative, i'm not sure if that's best way go.

you add random function, we'll use rand(0,1) generate 0 or 1, if it's 1 $status = 1 if it's 0 $status = -1. when return value multiplication $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;     } } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -