fork(1) download
  1. <pre>
  2. <?php
  3.  
  4. $seed = time(); // quite bad choice of seed
  5.  
  6. mt_srand($seed);
  7. echo "Seed: $seed, Random: ".random_bits(512)."\n";
  8.  
  9. mt_srand($seed);
  10. echo "Seed: $seed, Random: ".random_bits(512)."\n";
  11.  
  12. $seed ^= 0x11fedead;
  13. mt_srand($seed);
  14. echo "Seed: $seed, Random: ".random_bits(512)."\n";
  15.  
  16.  
  17. // Counts how many bits are needed to represent $value
  18. function count_bits($value) {
  19. for($count = 0; $value != 0; $value >>= 1) {
  20. ++$count;
  21. }
  22. return $count;
  23. }
  24.  
  25. // Returns a base16 random string of at least $bits bits
  26. // Actual bits returned will be a multiple of 4 (1 hex digit)
  27. function random_bits($bits) {
  28. $result = '';
  29. $accumulated_bits = 0;
  30. $total_bits = count_bits(mt_getrandmax());
  31. $usable_bits = intval($total_bits / 8) * 8;
  32.  
  33. while ($accumulated_bits < $bits) {
  34. $bits_to_add = min($total_bits - $usable_bits, $bits - $accumulated_bits);
  35. if ($bits_to_add % 4 != 0) {
  36. // add bits in whole increments of 4
  37. $bits_to_add += 4 - $bits_to_add % 4;
  38. }
  39.  
  40. // isolate leftmost $bits_to_add from mt_rand() result
  41. $more_bits = mt_rand() & ((1 << $bits_to_add) - 1);
  42.  
  43. // format as hex (this will be safe)
  44. $format_string = '%0'.($bits_to_add / 4).'x';
  45. $result .= sprintf($format_string, $more_bits);
  46. $accumulated_bits += $bits_to_add;
  47. }
  48.  
  49. return $result;
  50. }
  51.  
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
<pre>
Seed: 1366412299, Random: f036f4be6e1c8bcbc0bdb4f62022b4a350f72596db120fbf43dbd29126780c111169b56a83532e9e345a226cd68d8dfa49383f3277dffc2e08a01fe419493b9f
Seed: 1366412299, Random: f036f4be6e1c8bcbc0bdb4f62022b4a350f72596db120fbf43dbd29126780c111169b56a83532e9e345a226cd68d8dfa49383f3277dffc2e08a01fe419493b9f
Seed: 1083118246, Random: df06be56ab5bc63a8dc01793a1707529bdf861ba2b12aa72e39ad13a62c6e858ce76980ba78a6ad96857e7f64a88ece90f2bbc53594176c3c1c6fdd99f925469