update page now

Voting

: max(eight, four)?
(Example: nine)

The Note You're Voting On

robert at scabserver dot com
21 years ago
I spent some time looking for how to generate a large random number, in the end I've settled for reading directly from /dev/urandom

I know this is a *nix only solution, but I figured that it might come in handy to someone else.

The value $size is the size in bits, it could be simplified greatly if you want the size in bytes, but bits was more helpful to what I needed.

<?php
function bcrand($size)
{
    $filename = "/dev/urandom";
    $handle = fopen($filename, "r");
    $bin_urand = fread($handle, ceil($size/8.0));
    fclose($handle);
    $mask = (($size % 8 < 5) ? '0' : '') . dechex(bindec(str_repeat('1', $size % 8))) . str_repeat('FF', floor($size/8));
    $binmask = pack("H*", $mask);
    $binrand = $binmask & $bin_urand;
    $hexnumber = unpack("H*", $binrand);
    $hexnumber = $hexnumber[''];
    $numlength = strlen($hexnumber);
    $decnumber = 0;
    for($x = 1; $x <= $numlength; $x++)
    {
        $place = $numlength - $x;
        $operand = hexdec(substr($hexnumber,$place,1));
        $exponent = bcpow(16,$x-1);
        $decValue = bcmul($operand, $exponent);
        $decnumber = bcadd($decValue, $decnumber);
    }
    return $decnumber;
}
?>

<< Back to user notes page

To Top