|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PhpBinaryReader\Type; |
|
4
|
|
|
|
|
5
|
|
|
use PhpBinaryReader\BinaryReader; |
|
6
|
|
|
use PhpBinaryReader\BitMask; |
|
7
|
|
|
|
|
8
|
|
|
class Int8 implements TypeInterface |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var string |
|
12
|
|
|
*/ |
|
13
|
|
|
private $endian = 'C'; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Returns an Unsigned 8-bit Integer (aka a single byte) |
|
17
|
|
|
* |
|
18
|
|
|
* @param \PhpBinaryReader\BinaryReader $br |
|
19
|
|
|
* @param null $length |
|
20
|
|
|
* @return int |
|
21
|
|
|
* @throws \OutOfBoundsException |
|
22
|
|
|
*/ |
|
23
|
50 |
|
public function read(BinaryReader &$br, $length = null) |
|
24
|
|
|
{ |
|
25
|
50 |
|
if (!$br->canReadBytes(1)) { |
|
26
|
4 |
|
throw new \OutOfBoundsException('Cannot read 8-bit int, it exceeds the boundary of the file'); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
50 |
|
$segment = $br->readFromHandle(1); |
|
30
|
|
|
|
|
31
|
50 |
|
$data = unpack($this->endian, $segment); |
|
32
|
50 |
|
$data = $data[1]; |
|
33
|
|
|
|
|
34
|
50 |
|
if ($br->getCurrentBit() != 0) { |
|
35
|
4 |
|
$data = $this->bitReader($br, $data); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
50 |
|
return $data; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Returns a Signed 8-bit Integer (aka a single byte) |
|
43
|
|
|
* |
|
44
|
|
|
* @param \PhpBinaryReader\BinaryReader $br |
|
45
|
|
|
* @return int |
|
46
|
|
|
*/ |
|
47
|
40 |
|
public function readSigned(&$br) |
|
48
|
|
|
{ |
|
49
|
40 |
|
$this->setEndian('c'); |
|
50
|
40 |
|
$value = $this->read($br); |
|
51
|
40 |
|
$this->setEndian('C'); |
|
52
|
|
|
|
|
53
|
40 |
|
return $value; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param \PhpBinaryReader\BinaryReader $br |
|
58
|
|
|
* @param int $data |
|
59
|
|
|
* @return int |
|
60
|
|
|
*/ |
|
61
|
4 |
|
private function bitReader(&$br, $data) |
|
62
|
|
|
{ |
|
63
|
4 |
|
$bitmask = new BitMask(); |
|
64
|
4 |
|
$loMask = $bitmask->getMask($br->getCurrentBit(), BitMask::MASK_LO); |
|
65
|
4 |
|
$hiMask = $bitmask->getMask($br->getCurrentBit(), BitMask::MASK_HI); |
|
66
|
4 |
|
$hiBits = $br->getNextByte() & $hiMask; |
|
67
|
4 |
|
$loBits = $data & $loMask; |
|
68
|
4 |
|
$br->setNextByte($data); |
|
69
|
|
|
|
|
70
|
4 |
|
return $hiBits | $loBits; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @param string $endian |
|
75
|
|
|
*/ |
|
76
|
41 |
|
public function setEndian($endian) |
|
77
|
|
|
{ |
|
78
|
41 |
|
$this->endian = $endian; |
|
79
|
41 |
|
} |
|
80
|
|
|
|
|
81
|
|
|
/** |
|
82
|
|
|
* @return string |
|
83
|
|
|
*/ |
|
84
|
1 |
|
public function getEndian() |
|
85
|
|
|
{ |
|
86
|
1 |
|
return $this->endian; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|