random_int
函数
random_int ( $min, $max )
- 参数
-
-
(int)
$min- Required: 是
-
(int)
$max- Required: 是
-
(int)
- 返回值
-
- (int)
- 定义位置
-
-
wp-includes/random_compat/random_int.php
, line 41
-
wp-includes/random_compat/random_int.php
- 引入
- –
- 弃用
- –
取一个$min和$max之间的随机整数,包括$min和$max。
function random_int($min, $max) { /** * Type and input logic checks * * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX) * (non-inclusive), it will sanely cast it to an int. If you it's equal to * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats * lose precision, so the operators might accidentally let a float * through. */ try { /** @var int $min */ $min = RandomCompat_intval($min); } catch (TypeError $ex) { throw new TypeError( 'random_int(): $min must be an integer' ); } try { /** @var int $max */ $max = RandomCompat_intval($max); } catch (TypeError $ex) { throw new TypeError( 'random_int(): $max must be an integer' ); } /** * Now that we've verified our weak typing system has given us an integer, * let's validate the logic then we can move forward with generating random * integers along a given range. */ if ($min > $max) { throw new Error( 'Minimum value must be less than or equal to the maximum value' ); } if ($max === $min) { return (int) $min; } /** * Initialize variables to 0 * * We want to store: * $bytes => the number of random bytes we need * $mask => an integer bitmask (for use with the &) operator * so we can minimize the number of discards */ $attempts = $bits = $bytes = $mask = $valueShift = 0; /** @var int $attempts */ /** @var int $bits */ /** @var int $bytes */ /** @var int $mask */ /** @var int $valueShift */ /** * At this point, $range is a positive number greater than 0. It might * overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to * a float and we will lose some precision. * * @var int|float $range */ $range = $max - $min; /** * Test for integer overflow: */ if (!is_int($range)) { /** * Still safely calculate wider ranges. * Provided by @CodesInChaos, @oittaa * * @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435 * * We use ~0 as a mask in this case because it generates all 1s * * @ref https://eval.in/400356 (32-bit) * @ref http://3v4l.org/XX9r5 (64-bit) */ $bytes = PHP_INT_SIZE; /** @var int $mask */ $mask = ~0; } else { /** * $bits is effectively ceil(log($range, 2)) without dealing with * type juggling */ while ($range > 0) { if ($bits % 8 === 0) { ++$bytes; } ++$bits; $range >>= 1; /** @var int $mask */ $mask = $mask 128) { throw new Exception( 'random_int: RNG is broken - too many rejections' ); } /** * Let's grab the necessary number of random bytes */ $randomByteString = random_bytes($bytes); /** * Let's turn $randomByteString into an integer * * This uses bitwise operators ( * 159 + 27904 + 3276800 + 201326592 => * 204631455 */ $val &= 0; for ($i = 0; $i $max || $val
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。