| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace CBOR\OtherObject; |
| 6 |
|
| 7 |
use Brick\Math\BigInteger; |
| 8 |
use CBOR\OtherObject as Base; |
| 9 |
use CBOR\Utils; |
| 10 |
use const INF; |
| 11 |
use InvalidArgumentException; |
| 12 |
use const NAN; |
| 13 |
use function strlen; |
| 14 |
|
| 15 |
final class SinglePrecisionFloatObject extends Base |
| 16 |
{ |
| 17 |
public static function supportedAdditionalInformation(): array |
| 18 |
{ |
| 19 |
return [self::OBJECT_SINGLE_PRECISION_FLOAT]; |
| 20 |
} |
| 21 |
|
| 22 |
public static function createFromFloat(float $number): self |
| 23 |
{ |
| 24 |
$value = match (true) { |
| 25 |
is_nan($number) => hex2bin('7FC00000'), |
| 26 |
is_infinite($number) && $number > 0 => hex2bin('7F800000'), |
| 27 |
is_infinite($number) && $number < 0 => hex2bin('FF800000'), |
| 28 |
default => (fn (): string => unpack('S', "\x01\x00")[1] === 1 ? strrev(pack('f', $number)) : pack( |
| 29 |
'f', |
| 30 |
$number |
| 31 |
))(), |
| 32 |
}; |
| 33 |
|
| 34 |
return new self(self::OBJECT_SINGLE_PRECISION_FLOAT, $value); |
| 35 |
} |
| 36 |
|
| 37 |
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base |
| 38 |
{ |
| 39 |
return new self($additionalInformation, $data); |
| 40 |
} |
| 41 |
|
| 42 |
public static function create(string $value): self |
| 43 |
{ |
| 44 |
if (strlen($value) !== 4) { |
| 45 |
throw new InvalidArgumentException('The value is not a valid single precision floating point'); |
| 46 |
} |
| 47 |
|
| 48 |
return new self(self::OBJECT_SINGLE_PRECISION_FLOAT, $value); |
| 49 |
} |
| 50 |
|
| 51 |
public function normalize(): float|int |
| 52 |
{ |
| 53 |
$exponent = $this->getExponent(); |
| 54 |
$mantissa = $this->getMantissa(); |
| 55 |
$sign = $this->getSign(); |
| 56 |
|
| 57 |
if ($exponent === 0) { |
| 58 |
$val = $mantissa * 2 ** (-(126 + 23)); |
| 59 |
} elseif ($exponent !== 0b11111111) { |
| 60 |
$val = ($mantissa + (1 << 23)) * 2 ** ($exponent - (127 + 23)); |
| 61 |
} else { |
| 62 |
$val = $mantissa === 0 ? INF : NAN; |
| 63 |
} |
| 64 |
|
| 65 |
return $sign * $val; |
| 66 |
} |
| 67 |
|
| 68 |
public function getExponent(): int |
| 69 |
{ |
| 70 |
$data = $this->data; |
| 71 |
Utils::assertString($data, 'Invalid data'); |
| 72 |
|
| 73 |
return Utils::binToBigInteger($data)->shiftedRight(23)->and(Utils::hexToBigInteger('ff'))->toInt(); |
| 74 |
} |
| 75 |
|
| 76 |
public function getMantissa(): int |
| 77 |
{ |
| 78 |
$data = $this->data; |
| 79 |
Utils::assertString($data, 'Invalid data'); |
| 80 |
|
| 81 |
return Utils::binToBigInteger($data)->and(Utils::hexToBigInteger('7fffff'))->toInt(); |
| 82 |
} |
| 83 |
|
| 84 |
public function getSign(): int |
| 85 |
{ |
| 86 |
$data = $this->data; |
| 87 |
Utils::assertString($data, 'Invalid data'); |
| 88 |
$sign = Utils::binToBigInteger($data)->shiftedRight(31); |
| 89 |
|
| 90 |
return $sign->isEqualTo(BigInteger::one()) ? -1 : 1; |
| 91 |
} |
| 92 |
} |