The IP value objects store their internal state as a binary string, which is not
easy for humans to understand. The Darsyn\IP\Util\Binary class is a collection
of static helper methods for dealing with such binary strings.
@throws \InvalidArgumentException \Darsyn\IP\Util\Binary::fromHex(string $hex): string
Because there are two hexadecimal characters per byte, the input string must be of a length that is a multiple of 2.
<?php
use Darsyn\IP\Util\Binary;
$hexString = '48656c6c6f21';
Binary::fromHex($hexString); // string("Hello!")@throws \InvalidArgumentException \Darsyn\IP\Util\Binary::toHex(string $hex): string
<?php
use Darsyn\IP\Util\Binary;
$binaryString = 'Hello!';
Binary::toHex($binaryString); // string("48656c6c6f21")@throws \InvalidArgumentException \Darsyn\IP\Util\Binary::fromHumanReadable(string $asciiBinarySequence): string
Because there are 8 bits per bytes, the input string must be of a length that is a multiple of 8.
<?php
use Darsyn\IP\Util\Binary;
$asciiBinary = '010010000110010101101100011011000110111100100001';
Binary::fromHumanReadable($asciiBinary); // string("Hello!")@throws \InvalidArgumentException \Darsyn\IP\Util\Binary::toHumanReadable(string $binary): string
<?php
use Darsyn\IP\Util\Binary;
$binaryString = 'Hello!';
Binary::toHumanReadable($asciiBinary); // string("010010000110010101101100011011000110111100100001")@throws \InvalidArgumentException @throws \Darsyn\IP\Exception\OverflowException \Darsyn\IP\Util\Binary::fromDecimalString(string $decimal, int $lengthInBytes): string
Converts a base-10 integer string, at any precision, into a big-endian binary
string of exactly $lengthInBytes bytes (padded with null bytes on the left).
An OverflowException is thrown when the value does not fit within the
requested length. GMP is used when the extension is loaded; a pure-PHP fallback
is used otherwise.
<?php
use Darsyn\IP\Util\Binary;
$decimalString = '5216694956355301425';
Binary::fromDecimalString($decimalString, 8); // string("Hello!01")\Darsyn\IP\Util\Binary::toDecimalString(string $binary): string
<?php
use Darsyn\IP\Util\Binary;
$binaryString = 'Hello!01';
Binary::toDecimalString($binaryString); // string("5216694956355301425")On some PHP installations, the Multibyte String extension can overload PHP's native string functions which, because we are working with arbitrary binary content, can incorrectly guess an encoding when attempting to transform this data (IP addresses have no text encoding).
Because of this, the Darsyn\IP\Util\MbString class is a collection of static
helper equivalents for PHP's core string functions which detect if the
mbstring extension is installed and appropriately call the correct function,
specifying the 8bit text encoding (treat each byte as individual character)
if required.
| Static Helper Method | Replaces the PHP function... |
|---|---|
MbString::getLength() |
str_len() |
MbString::subString() |
substr() |
MbString::padString() |
str_pad() |