0

I try to create integers from raw-data that I read from '/dev/urandom'. But I do not know how to convert to an integer.

<?php

//////////////////////////////////////////////////////////////////////////////

function base62_encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
   if(!isset($base))
        $base = strlen($chars);
    $str = '';
    do {
        $m = bcmod($val, $base);
        $str = $chars[$m] . $str;
        $val = bcdiv(bcsub($val, $m), $base);
    } while(bccomp($val,0)>0);
    return $str;
}

//////////////////////////////////////////////////////////////////////////////

$file = fopen('/dev/urandom', 'rb');
if ( !$file ) {
   throw new Exception('Error!');
} else {
    $binary = fread($file, 4); // 4 bytes == 32 bits
   fclose($file);
   $dec = (int)$binary;
    $base62 = base62_encode($dec);

   fprintf(STDOUT, "dec:%d, %s\n", $dec, $base62);
}

//////////////////////////////////////////////////////////////////////////////

?>

As output I get: "dec:0, 0"

You can test code here.

niXman
  • 1,698
  • 3
  • 16
  • 40
  • @GordonM, Please look the code, I use '(int)$binary' but without success. – niXman Jan 18 '13 at 21:35
  • Is this guy trying to do the same thing? http://stackoverflow.com/questions/10363465/can-i-access-dev-urandom-with-open-basedir-in-effect – craig1231 Jan 18 '13 at 21:45

1 Answers1

2
$dec = unpack('L', $binary)[1];
mike
  • 7,137
  • 2
  • 23
  • 27