note 42915 added to ref.bc

From: Date: Thu, 03 Jun 2004 13:58:59 +0000
Subject: note 42915 added to ref.bc
Groups: php.notes 
Request: Send a blank email to php-notes+get-70649@lists.php.net to get a copy of this message
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; } ?> ---- Manual Page -- http://www.php.net/manual/en/ref.bc.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+42915 Delete -- http://master.php.net/manage/user-notes.php?action=delete+42915&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+42915&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#70649) next »