1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace RouterOS\Helpers; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* class BinaryStringHelper |
7
|
|
|
* |
8
|
|
|
* Strings and binary data manipulations |
9
|
|
|
* |
10
|
|
|
* @package RouterOS\Helpers |
11
|
|
|
* @since 0.9 |
12
|
|
|
*/ |
13
|
|
|
class BinaryStringHelper |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Convert an integer value in a "Network Byte Ordered" binary string (most significant value first) |
17
|
|
|
* |
18
|
|
|
* Reads the integer, starting from the most significant byte, one byte a time. |
19
|
|
|
* Once reach a non 0 byte, construct a binary string representing this values |
20
|
|
|
* ex : |
21
|
|
|
* 0xFF7 => chr(0x0F).chr(0xF7) |
22
|
|
|
* 0x12345678 => chr(0x12).chr(0x34).chr(0x56).chr(0x76) |
23
|
|
|
* Compatible with 8, 16, 32, 64 etc.. bits systems |
24
|
|
|
* |
25
|
|
|
* @see https://en.wikipedia.org/wiki/Endianness |
26
|
|
|
* @param int|float $value the integer value to be converted |
27
|
|
|
* @return string the binary string |
28
|
|
|
*/ |
29
|
16 |
|
public static function IntegerToNBOBinaryString($value): string |
30
|
|
|
{ |
31
|
|
|
// Initialize an empty string |
32
|
16 |
|
$buffer = ''; |
33
|
|
|
|
34
|
|
|
// Lets start from the most significant byte |
35
|
16 |
|
for ($i = (PHP_INT_SIZE - 1); $i >= 0; $i--) { |
36
|
|
|
// Prepare a mask to keep only the most significant byte of $value |
37
|
16 |
|
$mask = 0xFF << ($i * 8); |
38
|
|
|
|
39
|
|
|
// If the most significant byte is not 0, the final string must contain it |
40
|
|
|
// If we have already started to construct the string (i.e. there are more signficant digits) |
41
|
|
|
// we must set the byte, even if it is a 0. |
42
|
|
|
// 0xFF00FF, for example, require to set the second byte byte with a 0 value |
43
|
16 |
|
if (($value & $mask) || $buffer !== '') { |
44
|
|
|
// Get the current byte by shifting it to least significant position and add it to the string |
45
|
|
|
// 0xFF12345678 => 0xFF |
46
|
15 |
|
$byte = $value >> (8 * $i); |
47
|
15 |
|
$buffer .= chr($byte); |
48
|
|
|
|
49
|
|
|
// Set the most significant byte to 0 so we can restart the process being shure |
50
|
|
|
// that the value is left padded with 0 |
51
|
|
|
// 0xFF12345678 => 0x12345678 |
52
|
|
|
// -1 = 0xFFFFF.... (number of F depend of PHP_INT_SIZE ) |
53
|
15 |
|
$mask = -1 >> ((PHP_INT_SIZE - $i) * 8); |
54
|
15 |
|
$value &= $mask; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// Special case, 0 will not fill the buffer, have to construct it manualy |
59
|
16 |
|
if (0 === $value) { |
60
|
13 |
|
$buffer = chr(0); |
61
|
|
|
} |
62
|
|
|
|
63
|
16 |
|
return $buffer; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|