Total Complexity | 5 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | <?php |
||
7 | final class Utilities |
||
8 | { |
||
9 | /** |
||
10 | * Swaps the given number from endian format (INT16, not to be confused with UINT16) |
||
11 | * |
||
12 | * @param int $number |
||
13 | * @return int |
||
14 | * @throws \OutOfRangeException |
||
15 | */ |
||
16 | 21 | public static function convertEndianness(int $number): int |
|
17 | { |
||
18 | 21 | if ($number > 65535) { |
|
19 | 1 | throw new \OutOfRangeException('This is an INT16 conversion, so the maximum is 65535'); |
|
20 | } |
||
21 | |||
22 | 20 | $finalNumber = hexdec( |
|
23 | // Invert first byte and make it a complete hexadecimal number |
||
24 | 20 | str_pad(dechex($number & 255), 2, '0', STR_PAD_LEFT) . |
|
25 | // Invert second byte and make a complete hexadecimal number |
||
26 | 20 | str_pad(dechex($number >> 8), 2, '0', STR_PAD_LEFT) |
|
27 | ); |
||
28 | |||
29 | 20 | return (int)$finalNumber; |
|
30 | } |
||
31 | |||
32 | /** |
||
33 | * Converts a number to a binary string that the MQTT protocol understands |
||
34 | * |
||
35 | * @param int $number |
||
36 | * @return string |
||
37 | * @throws \OutOfRangeException |
||
38 | */ |
||
39 | 20 | public static function convertNumberToBinaryString(int $number): string |
|
40 | { |
||
41 | 20 | if ($number > 65535) { |
|
42 | 1 | throw new \OutOfRangeException('This is an INT16 conversion, so the maximum is 65535'); |
|
43 | } |
||
44 | |||
45 | 19 | return \chr($number >> 8) . \chr($number & 255); |
|
46 | } |
||
47 | |||
48 | /** |
||
49 | * Converts a binary representation of a number to an actual int |
||
50 | * |
||
51 | * @param string $binaryString |
||
52 | * @return int |
||
53 | * @throws \OutOfRangeException |
||
54 | */ |
||
55 | 12 | public static function convertBinaryStringToNumber(string $binaryString): int |
|
58 | } |
||
59 | } |
||
60 |