function BigInteger::toBytes
Returns a string of bytes containing the binary representation of this BigInteger.
The string is in big-endian byte-order: the most significant byte is in the zeroth element.
If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the number is negative.
The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit if `$signed` is true.
This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
Parameters
bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.:
Throws
NegativeNumberException If $signed is false, and the number is negative.
File
-
vendor/
brick/ math/ src/ BigInteger.php, line 975
Class
- BigInteger
- An arbitrary-size integer.
Namespace
Brick\MathCode
public function toBytes(bool $signed = true) : string {
if (!$signed && $this->isNegative()) {
throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
}
$hex = $this->abs()
->toBase(16);
if (\strlen($hex) % 2 !== 0) {
$hex = '0' . $hex;
}
$baseHexLength = \strlen($hex);
if ($signed) {
if ($this->isNegative()) {
$bin = \hex2bin($hex);
assert($bin !== false);
$hex = \bin2hex(~$bin);
$hex = self::fromBase($hex, 16)->plus(1)
->toBase(16);
$hexLength = \strlen($hex);
if ($hexLength < $baseHexLength) {
$hex = \str_repeat('0', $baseHexLength - $hexLength) . $hex;
}
if ($hex[0] < '8') {
$hex = 'FF' . $hex;
}
}
else {
if ($hex[0] >= '8') {
$hex = '00' . $hex;
}
}
}
return \hex2bin($hex);
}