1 | <?php |
||
12 | class Flags |
||
13 | { |
||
14 | /** |
||
15 | * Flag octets. |
||
16 | * |
||
17 | * @var string $_flags |
||
18 | */ |
||
19 | protected $_flags; |
||
20 | |||
21 | /** |
||
22 | * Number of flags. |
||
23 | * |
||
24 | * @var int $_width |
||
25 | */ |
||
26 | protected $_width; |
||
27 | |||
28 | /** |
||
29 | * Constructor. |
||
30 | * |
||
31 | * @param int|string $flags Flags |
||
32 | * @param int $width The number of flags. If width is larger than number of |
||
33 | * bits in $flags, zeroes are prepended to flag field. |
||
34 | */ |
||
35 | 62 | public function __construct($flags, int $width) |
|
61 | |||
62 | /** |
||
63 | * Initialize from BitString. |
||
64 | * |
||
65 | * @param BitString $bs |
||
66 | * @param int $width |
||
67 | * @return self |
||
68 | */ |
||
69 | 8 | public static function fromBitString(BitString $bs, int $width): self |
|
70 | { |
||
71 | 8 | $num_bits = $bs->numBits(); |
|
72 | 8 | $num = gmp_import($bs->string(), 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN); |
|
73 | 8 | $num >>= $bs->unusedBits(); |
|
74 | 8 | if ($num_bits < $width) { |
|
75 | 5 | $num <<= ($width - $num_bits); |
|
76 | } |
||
77 | 8 | return new self(gmp_strval($num, 10), $width); |
|
78 | } |
||
79 | |||
80 | /** |
||
81 | * Check whether a bit at given index is set. |
||
82 | * Index 0 is the leftmost bit. |
||
83 | * |
||
84 | * @param int $idx |
||
85 | * @throws \OutOfBoundsException |
||
86 | * @return bool |
||
87 | */ |
||
88 | 15 | public function test(int $idx): bool |
|
102 | |||
103 | /** |
||
104 | * Get flags as an octet string. |
||
105 | * Zeroes are appended to the last octet if width is not divisible by 8. |
||
106 | * |
||
107 | * @return string |
||
108 | */ |
||
109 | 23 | public function string(): string |
|
113 | |||
114 | /** |
||
115 | * Get flags as a base 10 integer. |
||
116 | * |
||
117 | * @return string Integer as a string |
||
118 | */ |
||
119 | 15 | public function number(): string |
|
127 | |||
128 | /** |
||
129 | * Get flags as an integer. |
||
130 | * |
||
131 | * @return int |
||
132 | */ |
||
133 | 1 | public function intNumber(): int |
|
138 | |||
139 | /** |
||
140 | * Get flags as a BitString. |
||
141 | * Unused bits are set accordingly. Trailing zeroes are not stripped. |
||
142 | * |
||
143 | * @return BitString |
||
144 | */ |
||
145 | 9 | public function bitString(): BitString |
|
151 | } |
||
152 |