function BigInteger::randomBits
Generates a pseudo-random number in the range 0 to 2^numBits - 1.
Using the default random bytes generator, this method is suitable for cryptographic use.
@psalm-param (callable(int): string)|null $randomBytesGenerator
Parameters
int $numBits The number of bits.:
callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, and returns a: string of random bytes of the given length. Defaults to the `random_bytes()` function.
Throws
\InvalidArgumentException If $numBits is negative.
1 call to BigInteger::randomBits()
- BigInteger::randomRange in vendor/
brick/ math/ src/ BigInteger.php - Generates a pseudo-random number between `$min` and `$max`.
File
-
vendor/
brick/ math/ src/ BigInteger.php, line 213
Class
- BigInteger
- An arbitrary-size integer.
Namespace
Brick\MathCode
public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null) : BigInteger {
if ($numBits < 0) {
throw new \InvalidArgumentException('The number of bits cannot be negative.');
}
if ($numBits === 0) {
return BigInteger::zero();
}
if ($randomBytesGenerator === null) {
$randomBytesGenerator = random_bytes(...);
}
/** @var int<1, max> $byteLength */
$byteLength = \intdiv($numBits - 1, 8) + 1;
$extraBits = $byteLength * 8 - $numBits;
$bitmask = \chr(0xff >> $extraBits);
$randomBytes = $randomBytesGenerator($byteLength);
$randomBytes[0] = $randomBytes[0] & $bitmask;
return self::fromBytes($randomBytes, false);
}