1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BitWasp\Buffertools\Types; |
6
|
|
|
|
7
|
|
|
use BitWasp\Buffertools\ByteOrder; |
8
|
|
|
use BitWasp\Buffertools\Parser; |
9
|
|
|
|
10
|
|
|
abstract class AbstractUint extends AbstractType implements UintInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param int $byteOrder |
14
|
|
|
*/ |
15
|
90 |
|
public function __construct(int $byteOrder = ByteOrder::BE) |
16
|
|
|
{ |
17
|
90 |
|
parent::__construct($byteOrder); |
18
|
88 |
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param int|string $integer - decimal integer |
22
|
|
|
* @return string |
23
|
|
|
*/ |
24
|
100 |
|
public function writeBits($integer): string |
25
|
|
|
{ |
26
|
100 |
|
return str_pad( |
27
|
100 |
|
gmp_strval(gmp_init($integer, 10), 2), |
28
|
100 |
|
$this->getBitSize(), |
29
|
100 |
|
'0', |
30
|
100 |
|
STR_PAD_LEFT |
31
|
|
|
); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param Parser $parser |
36
|
|
|
* @return int|string |
37
|
|
|
* @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange |
38
|
|
|
* @throws \Exception |
39
|
|
|
*/ |
40
|
102 |
|
public function readBits(Parser $parser) |
41
|
|
|
{ |
42
|
102 |
|
$bitSize = $this->getBitSize(); |
43
|
102 |
|
$bits = str_pad( |
44
|
102 |
|
gmp_strval(gmp_init($parser->readBytes($bitSize / 8)->getHex(), 16), 2), |
45
|
102 |
|
$bitSize, |
46
|
102 |
|
'0', |
47
|
102 |
|
STR_PAD_LEFT |
48
|
|
|
); |
49
|
|
|
|
50
|
102 |
|
$finalBits = $this->isBigEndian() |
51
|
48 |
|
? $bits |
52
|
102 |
|
: $this->flipBits($bits); |
53
|
|
|
|
54
|
102 |
|
$integer = gmp_strval(gmp_init($finalBits, 2), 10); |
55
|
|
|
|
56
|
102 |
|
return $integer; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* {@inheritdoc} |
61
|
|
|
* @see \BitWasp\Buffertools\Types\TypeInterface::write() |
62
|
|
|
*/ |
63
|
100 |
|
public function write($integer): string |
64
|
|
|
{ |
65
|
100 |
|
return pack( |
66
|
100 |
|
"H*", |
67
|
100 |
|
str_pad( |
68
|
100 |
|
gmp_strval( |
69
|
100 |
|
gmp_init( |
70
|
100 |
|
$this->isBigEndian() |
71
|
48 |
|
? $this->writeBits($integer) |
72
|
100 |
|
: $this->flipBits($this->writeBits($integer)), |
73
|
100 |
|
2 |
74
|
|
|
), |
75
|
100 |
|
16 |
76
|
|
|
), |
77
|
100 |
|
$this->getBitSize()/4, |
78
|
100 |
|
'0', |
79
|
100 |
|
STR_PAD_LEFT |
80
|
|
|
) |
81
|
|
|
); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* {@inheritdoc} |
86
|
|
|
* @see \BitWasp\Buffertools\Types\TypeInterface::read() |
87
|
|
|
*/ |
88
|
102 |
|
public function read(Parser $binary) |
89
|
|
|
{ |
90
|
102 |
|
return $this->readBits($binary); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|