1 | <?php |
||
17 | class BitBuffer{ |
||
18 | |||
19 | /** @var int[] */ |
||
20 | public array $buffer = []; |
||
|
|||
21 | |||
22 | public int $length = 0; |
||
23 | |||
24 | /** |
||
25 | * |
||
26 | */ |
||
27 | public function clear():BitBuffer{ |
||
28 | $this->buffer = []; |
||
29 | $this->length = 0; |
||
30 | |||
31 | return $this; |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * |
||
36 | */ |
||
37 | public function put(int $num, int $length):BitBuffer{ |
||
38 | |||
39 | for($i = 0; $i < $length; $i++){ |
||
40 | $this->putBit((($num >> ($length - $i - 1)) & 1) === 1); |
||
41 | } |
||
42 | |||
43 | return $this; |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * |
||
48 | */ |
||
49 | public function putBit(bool $bit):BitBuffer{ |
||
50 | $bufIndex = floor($this->length / 8); |
||
51 | |||
52 | if(count($this->buffer) <= $bufIndex){ |
||
53 | $this->buffer[] = 0; |
||
54 | } |
||
55 | |||
56 | if($bit === true){ |
||
57 | $this->buffer[(int)$bufIndex] |= (0x80 >> ($this->length % 8)); |
||
58 | } |
||
59 | |||
60 | $this->length++; |
||
61 | |||
62 | return $this; |
||
63 | } |
||
64 | |||
65 | } |
||
66 |