PHP & Laravel

Binary Tools (PHP)

A PHP library for binary data manipulation and encoding/decoding operations. This library provides safe, efficient tools for working with binary data, including UTF-8 validation and secure string comparisons.

Installation

composer require kduma/binary-tools

Requirements

  • PHP 8.4+
  • ext-mbstring - For UTF-8 validation
  • ext-hash - For secure string comparisons

Features

  • Safe binary data manipulation with bounds checking
  • UTF-8 string validation for text data
  • Multiple encoding formats (hex, base64, base32)
  • Secure string comparison using hash_equals()
  • Binary-safe substring search with BinaryString::contains()
  • Flexible integer support with configurable byte order and signedness
  • Position tracking for streaming operations
  • Terminator support for null-terminated and delimited data parsing
  • Fixed-size field padding with configurable pad byte support

Core Classes

BinaryString

Immutable wrapper for binary data with conversion and comparison methods.

BinaryWriter

Stream-like writer for building binary data structures.

BinaryReader

Stream-like reader for parsing binary data with position tracking.

IntType

Enum defining integer types with configurable byte order, signedness, and platform validation.

Terminator

Enum defining common binary terminators for delimited data parsing.

Usage Examples

BinaryString

use KDuma\BinaryTools\BinaryString;

// Create from different sources
$binary = BinaryString::fromString("\x48\x65\x6c\x6c\x6f");
$fromString = BinaryString::fromString("Hello");
$fromHex = BinaryString::fromHex("48656c6c6f");
$fromBase64 = BinaryString::fromBase64("SGVsbG8=");
$fromBase32 = BinaryString::fromBase32("JBSWY3DP");

// All represent "Hello"
echo $binary->toString(); // "Hello"

// Convert to different formats
echo $binary->toHex();    // "48656c6c6f"
echo $binary->toBase64(); // "SGVsbG8="
echo $binary->toBase32(); // "JBSWY3DP"
echo $binary->size();     // 5

// Secure comparison
$other = BinaryString::fromString("Hello");
if ($binary->equals($other)) {
    echo "Strings are equal";
}

// Binary-safe substring search
if ($binary->contains(BinaryString::fromString("He"))) {
    echo "Binary data contains 'He'";
}

BinaryWriter

use KDuma\BinaryTools\BinaryWriter;
use KDuma\BinaryTools\BinaryString;
use KDuma\BinaryTools\IntType;

$writer = new BinaryWriter();

// Write different data types
$writer->writeByte(0x42)                          // Single byte
       ->writeInt(IntType::UINT16, 1234)          // 16-bit unsigned integer
       ->writeInt(IntType::INT32_LE, -500)        // 32-bit signed little-endian
       ->writeBytes(BinaryString::fromHex("abcd")) // Raw bytes
       ->writeString(BinaryString::fromString("Hello")); // UTF-8 string

// Write strings with length prefixes
$text = BinaryString::fromString("Hello World");
$writer->writeStringWith($text, length: IntType::UINT8);   // 8-bit length + string
$writer->writeStringWith($text, length: IntType::UINT16);  // 16-bit length + string
$writer->writeBytesWith(BinaryString::fromHex("abcd"), length: IntType::UINT16_LE); // Little-endian length + bytes

// Write strings with terminators
$writer->writeStringWith($text, terminator: Terminator::NUL);  // Null-terminated string
$writer->writeBytesWith($data, terminator: BinaryString::fromString("\r\n")); // Custom terminator

// Write fixed-size fields with padding
$writer->writeBytesWith(BinaryString::fromString('OK'), padding: BinaryString::fromString("\x20"), padding_size: 4);
$writer->writeStringWith(BinaryString::fromString('ID'), padding_size: 4); // Defaults to NUL padding

// Get the result
$result = $writer->getBuffer();
echo $result->toHex(); // Complete binary data as hex

BinaryReader

use KDuma\BinaryTools\BinaryReader;
use KDuma\BinaryTools\BinaryString;
use KDuma\BinaryTools\IntType;

$data = BinaryString::fromHex("4204d2abcd48656c6c6f0548656c6c6f20576f726c64000b48656c6c6f20576f726c64");
$reader = new BinaryReader($data);

// Read different data types
$byte = $reader->readByte();                    // 0x42
$uint16 = $reader->readInt(IntType::UINT16);    // 1234
$int32le = $reader->readInt(IntType::INT32_LE); // Little-endian 32-bit signed
$bytes = $reader->readBytes(2);                 // BinaryString with raw bytes
$stringData = $reader->readString(5);           // BinaryString with UTF-8 validation
$string = $stringData->toString();              // "Hello" - actual string value

// Read strings with length prefixes
$stringWithLength = $reader->readStringWith(length: IntType::UINT8);   // 8-bit length
$stringWithLength16 = $reader->readStringWith(length: IntType::UINT16); // 16-bit length
$bytesWithLength = $reader->readBytesWith(length: IntType::UINT16_LE);  // Little-endian length + bytes

// Read strings with terminators
$nullTermString = $reader->readStringWith(terminator: Terminator::NUL);  // Terminator required
$lineData = $reader->readBytesWith(optional_terminator: BinaryString::fromString("\r\n")); // Terminator optional

// Read padded fields (total size includes padding)
$status = $reader->readBytesWith(padding: BinaryString::fromString("\x20"), padding_size: 4);
$identifier = $reader->readStringWith(padding_size: 4); // Defaults to NUL padding

// Position management
echo $reader->position;        // Current position
echo $reader->remaining_bytes; // Bytes left
echo $reader->has_more_data;   // Boolean

// Peek without advancing
$nextByte = $reader->peekByte();
$next3Bytes = $reader->peekBytes(3);

// Seek to specific position
$reader->seek(0);  // Go to start
$reader->skip(5);  // Skip 5 bytes

📝 Reading Strings vs Binary Data

  • Use readString(length) for UTF-8 text data that needs validation
  • Use readBytes(length) for raw binary data (magic bytes, checksums, etc.)
  • Use readStringWith(length: IntType) for strings with typed length prefixes
  • Use readBytesWith(length: IntType) for binary data with typed length prefixes
  • Use readStringWith(terminator: Terminator|BinaryString) when the terminator must be present
  • Use readStringWith(optional_terminator: Terminator|BinaryString) to read until terminator or end of data
  • Use readBytesWith(terminator: Terminator|BinaryString) when the terminator must be present
  • Use readBytesWith(optional_terminator: Terminator|BinaryString) to read until terminator or end of data
  • Use readBytesWith(padding_size: int, padding: Terminator|BinaryString) for fixed-size padded fields (pad byte must be single byte and absent from data)
  • Terminator arguments must be non-empty in both modes
  • Call toString() on BinaryString objects to get actual string values

Terminator Support

The library supports both length-prefixed and terminator-delimited data parsing:

use KDuma\BinaryTools\BinaryWriter;
use KDuma\BinaryTools\BinaryReader;
use KDuma\BinaryTools\BinaryString;
use KDuma\BinaryTools\Terminator;

// Create some data with different delimiters
$writer = new BinaryWriter();

// Null-terminated string (C-style)
$writer->writeStringWith(BinaryString::fromString("Hello World"), terminator: Terminator::NUL);

// Line-based data with CRLF terminator
$writer->writeBytesWith(BinaryString::fromString("Line 1"), terminator: BinaryString::fromString("\r\n"));
$writer->writeBytesWith(BinaryString::fromString("Line 2"), terminator: BinaryString::fromString("\r\n"));

// Group separator terminated data
$writer->writeStringWith(BinaryString::fromString("Record 1"), terminator: Terminator::GS);

// Read the data back
$reader = new BinaryReader($writer->getBuffer());

$nullTermString = $reader->readStringWith(terminator: Terminator::NUL);
echo $nullTermString->toString(); // "Hello World"

$line1 = $reader->readBytesWith(terminator: BinaryString::fromString("\r\n"));
$line2 = $reader->readBytesWith(terminator: BinaryString::fromString("\r\n"));
echo $line1->toString() . " and " . $line2->toString(); // "Line 1 and Line 2"

$record = $reader->readStringWith(terminator: Terminator::GS);
echo $record->toString(); // "Record 1"

Available Terminators

TerminatorValueDescription
Terminator::NUL\x00Null character (C-style strings)
Terminator::SOH\x01Start of Heading
Terminator::STX\x02Start of Text
Terminator::ETX\x03End of Text
Terminator::EOT\x04End of Transmission
Terminator::ENQ\x05Enquiry
Terminator::ACK\x06Acknowledge
Terminator::BEL\x07Bell
Terminator::BS\x08Backspace
Terminator::HT\x09Horizontal Tab
Terminator::LF\x0ALine Feed
Terminator::VT\x0BVertical Tab
Terminator::FF\x0CForm Feed
Terminator::CR\x0DCarriage Return
Terminator::SO\x0EShift Out
Terminator::SI\x0FShift In
Terminator::DLE\x10Data Link Escape
Terminator::DC1\x11Device Control 1 (XON)
Terminator::DC2\x12Device Control 2
Terminator::DC3\x13Device Control 3 (XOFF)
Terminator::DC4\x14Device Control 4
Terminator::NAK\x15Negative Acknowledge
Terminator::SYN\x16Synchronous Idle
Terminator::ETB\x17End of Transmission Block
Terminator::CAN\x18Cancel
Terminator::EM\x19End of Medium
Terminator::SUB\x1ASubstitute
Terminator::ESC\x1BEscape
Terminator::FS\x1CFile Separator
Terminator::GS\x1DGroup Separator
Terminator::RS\x1ERecord Separator
Terminator::US\x1FUnit Separator
Terminator::SP\x20Space
Terminator::CRLF\x0D\x0ACarriage Return + Line Feed
Custom BinaryStringAny bytesCustom terminator sequence

Common Use Cases

Protocol Implementation

// Writing a simple protocol message
$writer = new BinaryWriter();
$message = BinaryString::fromString("Hello, Protocol!");

$writer->writeByte(0x01)                           // Message type
       ->writeInt(IntType::UINT16, time() & 0xFFFF) // Timestamp (16-bit)
       ->writeStringWith($message, length: IntType::UINT8); // Payload

$packet = $writer->getBuffer();

// Reading the protocol message
$reader = new BinaryReader($packet);
$messageType = $reader->readByte();
$timestamp = $reader->readInt(IntType::UINT16);
$payload = $reader->readStringWith(length: IntType::UINT8);

echo "Type: {$messageType}, Time: {$timestamp}, Message: {$payload->toString()}";

File Header Parsing

// Parse a file with magic bytes and metadata
$fileData = BinaryString::fromHex("4d5a90000300000004000000ffff0000");
$reader = new BinaryReader($fileData);

$magic = $reader->readBytes(2)->toString();  // "MZ"
if ($magic === "MZ") {
    $bytesOnLastPage = $reader->readInt(IntType::UINT16);
    $pagesInFile = $reader->readInt(IntType::UINT16);
    // ... continue parsing
}

Data Serialization

// Serialize complex data
$writer = new BinaryWriter();

$users = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
];

$writer->writeByte(count($users)); // User count

foreach ($users as $user) {
    $writer->writeInt(IntType::UINT16, $user['id']);
    $writer->writeStringWith(BinaryString::fromString($user['name']), length: IntType::UINT8);
}

$serialized = $writer->getBuffer();

// Deserialize
$reader = new BinaryReader($serialized);
$userCount = $reader->readByte();

for ($i = 0; $i < $userCount; $i++) {
    $userId = $reader->readInt(IntType::UINT16);
    $userName = $reader->readStringWith(length: IntType::UINT8)->toString();
    echo "User {$userId}: {$userName}\n";
}

API Reference

BinaryString

MethodDescription
toString(): stringGet raw binary data
toHex(): stringConvert to hexadecimal string
toBase64(): stringConvert to base64 string
toBase32(string $alphabet = Base32::DEFAULT_ALPHABET): stringConvert to base32 string
size(): intGet byte length
equals(BinaryString $other): boolSecure comparison
fromString(string $value): staticCreate from string
fromHex(string $hex): staticCreate from hex string
fromBase64(string $base64): staticCreate from base64
fromBase32(string $base32, string $alphabet = Base32::DEFAULT_ALPHABET): staticCreate from base32 string

BinaryWriter

MethodDescription
getBuffer(): BinaryStringGet written data
getLength(): intGet buffer length
reset(): voidClear buffer
writeByte(int $byte): selfWrite single byte (0-255)
writeBytes(BinaryString $bytes): selfWrite binary data
writeInt(IntType $type, int $value): selfWrite integer with specified type
writeString(BinaryString $string): selfWrite UTF-8 string
writeBytesWith(BinaryString $bytes, ?IntType $length = null, Terminator|BinaryString|null $terminator = null, Terminator|BinaryString|null $padding = null, ?int $padding_size = null): selfWrite bytes with length prefix, terminator, or fixed padding
writeStringWith(BinaryString $string, ?IntType $length = null, Terminator|BinaryString|null $terminator = null, Terminator|BinaryString|null $padding = null, ?int $padding_size = null): selfWrite string with length prefix, terminator, or fixed padding

BinaryReader

Property/MethodDescription
$positionCurrent read position
$lengthTotal data length
$remaining_bytesBytes remaining
$has_more_dataWhether more data available
$dataGet original data as BinaryString
$remaining_dataGet remaining data
readByte(): intRead single byte
readBytes(int $count): BinaryStringRead N bytes
readInt(IntType $type): intRead integer with specified type
readString(int $length): BinaryStringRead UTF-8 string of specific length
readBytesWith(?IntType $length = null, Terminator|BinaryString|null $terminator = null, Terminator|BinaryString|null $optional_terminator = null, Terminator|BinaryString|null $padding = null, ?int $padding_size = null): BinaryStringRead bytes with length prefix, terminator, or fixed padding
readStringWith(?IntType $length = null, Terminator|BinaryString|null $terminator = null, Terminator|BinaryString|null $optional_terminator = null, Terminator|BinaryString|null $padding = null, ?int $padding_size = null): BinaryStringRead string with length prefix, terminator, or fixed padding
peekByte(): intPeek next byte without advancing
peekBytes(int $count): BinaryStringPeek N bytes without advancing
seek(int $position): voidSeek to position
skip(int $count): voidSkip N bytes

IntType

The IntType enum defines various integer types with different byte sizes, signedness, and byte order.

TypeBytesSignedLittle EndianMin ValueMax ValuePlatform Support
UINT81NoN/A0255Always
INT81YesN/A-128127Always
UINT162NoNo065535Always
INT162YesNo-3276832767Always
UINT16_LE2NoYes065535Always
INT16_LE2YesYes-3276832767Always
UINT324NoNo04294967295Always
INT324YesNo-21474836482147483647Always
UINT32_LE4NoYes04294967295Always
INT32_LE4YesYes-21474836482147483647Always
UINT648NoNo0PHP_INT_MAX*64-bit only
INT648YesNoPHP_INT_MIN*PHP_INT_MAX*64-bit only
UINT64_LE8NoYes0PHP_INT_MAX*64-bit only
INT64_LE8YesYesPHP_INT_MIN*PHP_INT_MAX*64-bit only

*64-bit types are limited by PHP's integer size on the platform.

IntType Methods

MethodDescription
bytes(): intGet byte size of the type
isSigned(): boolWhether the type is signed
isLittleEndian(): boolWhether the type uses little-endian byte order
isSupported(): boolWhether the type is supported on current platform
minValue(): intGet minimum valid value for the type
maxValue(): intGet maximum valid value for the type
isValid(int $value): boolCheck if value is within valid range

Terminator

MethodDescription
toBytes(): BinaryStringGet terminator as binary bytes

Available Cases:

  • Terminator::NUL - Null character (\x00)
  • Terminator::SOH - Start of Heading (\x01)
  • Terminator::STX - Start of Text (\x02)
  • Terminator::ETX - End of Text (\x03)
  • Terminator::EOT - End of Transmission (\x04)
  • Terminator::ENQ - Enquiry (\x05)
  • Terminator::ACK - Acknowledge (\x06)
  • Terminator::BEL - Bell (\x07)
  • Terminator::BS - Backspace (\x08)
  • Terminator::HT - Horizontal Tab (\x09)
  • Terminator::LF - Line Feed (\x0A)
  • Terminator::VT - Vertical Tab (\x0B)
  • Terminator::FF - Form Feed (\x0C)
  • Terminator::CR - Carriage Return (\x0D)
  • Terminator::SO - Shift Out (\x0E)
  • Terminator::SI - Shift In (\x0F)
  • Terminator::DLE - Data Link Escape (\x10)
  • Terminator::DC1 - Device Control 1 (XON) (\x11)
  • Terminator::DC2 - Device Control 2 (\x12)
  • Terminator::DC3 - Device Control 3 (XOFF) (\x13)
  • Terminator::DC4 - Device Control 4 (\x14)
  • Terminator::NAK - Negative Acknowledge (\x15)
  • Terminator::SYN - Synchronous Idle (\x16)
  • Terminator::ETB - End of Transmission Block (\x17)
  • Terminator::CAN - Cancel (\x18)
  • Terminator::EM - End of Medium (\x19)
  • Terminator::SUB - Substitute (\x1A)
  • Terminator::ESC - Escape (\x1B)
  • Terminator::FS - File Separator (\x1C)
  • Terminator::GS - Group Separator (\x1D)
  • Terminator::RS - Record Separator (\x1E)
  • Terminator::US - Unit Separator (\x1F)
  • Terminator::SP - Space (\x20)
  • Terminator::CRLF - Carriage Return + Line Feed (\x0D\x0A)

Deprecated Methods

The following methods are deprecated but remain available for backward compatibility:

  • BinaryWriter::writeUint16BE(int $value) - Use writeInt(IntType::UINT16, $value) instead
  • BinaryWriter::writeBytesWithLength(BinaryString $bytes, bool $use16BitLength = false) - Use writeBytesWith($bytes, length: IntType $length) instead
  • BinaryWriter::writeStringWithLength(BinaryString $string, bool $use16BitLength = false) - Use writeStringWith($string, length: IntType $length) instead
  • BinaryReader::readUint16BE() - Use readInt(IntType::UINT16) instead
  • BinaryReader::readBytesWithLength(bool $use16BitLength = false) - Use readBytesWith(length: IntType::UINT8) instead
  • BinaryReader::readStringWithLength(bool $use16BitLength = false) - Use readStringWith(length: IntType::UINT8) instead

Error Handling

The library throws appropriate exceptions for error conditions:

  • InvalidArgumentException - Invalid parameters (e.g., byte values > 255, invalid Base32 alphabet, invalid Base32 characters)
  • RuntimeException - Runtime errors (e.g., reading past end of data, invalid UTF-8)
try {
    $reader = new BinaryReader(BinaryString::fromHex("41"));
    $reader->readBytes(5); // Trying to read more than available
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}

Binary Tools for PHP - API Reference

This documentation is auto-generated from the source code.

Table of Contents

BinaryString

Namespace: KDuma\BinaryTools

Type: Final Class

Properties

$value

string $value

Methods

toString()
\KDuma\BinaryTools\BinaryString::toString(): string

Returns the raw binary value as a PHP string.

Returns: string


toHex()
\KDuma\BinaryTools\BinaryString::toHex(): string

Serialises the binary value into an ASCII hexadecimal string.

Returns: string


toBase64()
\KDuma\BinaryTools\BinaryString::toBase64(): string

Serialises the binary value using Base64 encoding.

Returns: string


toBase32(...)
\KDuma\BinaryTools\BinaryString::toBase32(
    string $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
): string

Returns a Base32-encoded string representation of the binary value.

ParamTypeDescription
alphabetstring (optional)Alphabet to use when encoding.

Returns: string


size()
\KDuma\BinaryTools\BinaryString::size(): int

Returns the number of bytes contained in the value.

Returns: int


fromString(...)
\KDuma\BinaryTools\BinaryString::fromString(
    string $value
): static

Creates a BinaryString from an existing PHP string without validation.

ParamTypeDescription
valuestringRaw binary data.

Returns: static


fromHex(...)
\KDuma\BinaryTools\BinaryString::fromHex(
    string $hex
): static

Creates a BinaryString from a hexadecimal dump.

ParamTypeDescription
hexstringHexadecimal representation of the data.

Returns: static


fromBase64(...)
\KDuma\BinaryTools\BinaryString::fromBase64(
    string $base64
): static

Creates a BinaryString from a Base64-encoded payload.

ParamTypeDescription
base64stringBase64 representation of the data.

Returns: static


fromBase32(...)
\KDuma\BinaryTools\BinaryString::fromBase32(
    string $base32,
    string $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
): static

Decodes a Base32-encoded string to a BinaryString instance using the specified alphabet.

ParamTypeDescription
base32stringBase32 payload to decode.
alphabetstring (optional)Alphabet that was used during encoding.

Returns: static


equals(...)
\KDuma\BinaryTools\BinaryString::equals(
    \KDuma\BinaryTools\BinaryString $other
): bool

Performs a timing-safe comparison with another BinaryString.

ParamTypeDescription
other\KDuma\BinaryTools\BinaryStringValue to compare against.

Returns: bool


contains(...)
\KDuma\BinaryTools\BinaryString::contains(
    \KDuma\BinaryTools\BinaryString $needle
): bool

Determines whether the provided binary fragment appears in the value.

ParamTypeDescription
needle\KDuma\BinaryTools\BinaryStringFragment to look for.

Returns: bool



BinaryWriter

Namespace: KDuma\BinaryTools

Type: Final Class

Methods

getBuffer()
\KDuma\BinaryTools\BinaryWriter::getBuffer(): \KDuma\BinaryTools\BinaryString

Returns the buffered bytes as a BinaryString without resetting the writer.

Returns: \KDuma\BinaryTools\BinaryString


getLength()
\KDuma\BinaryTools\BinaryWriter::getLength(): int

Returns the number of bytes written so far.

Returns: int


reset()
\KDuma\BinaryTools\BinaryWriter::reset(): void

Clears the buffer so subsequent writes start from an empty state.

Returns: void


writeByte(...)
\KDuma\BinaryTools\BinaryWriter::writeByte(
    int $byte
): self

Appends a single byte value (0-255) to the buffer.

Throws: \InvalidArgumentException When the value is outside the valid byte range.

ParamTypeDescription
byteintByte value to write.

Returns: self


writeBytes(...)
\KDuma\BinaryTools\BinaryWriter::writeBytes(
    \KDuma\BinaryTools\BinaryString $bytes
): self

Appends raw bytes to the buffer.

ParamTypeDescription
bytes\KDuma\BinaryTools\BinaryStringData to append.

Returns: self


writeBytesWith(...)
\KDuma\BinaryTools\BinaryWriter::writeBytesWith(
    \KDuma\BinaryTools\BinaryString $bytes,
    ?\KDuma\BinaryTools\IntType $length = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $optional_terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $padding = null,
    ?int $padding_size = null
): self

Writes variable-length data using one of the available strategies: typed length, terminator or fixed padding.

Throws: \InvalidArgumentException When configuration is invalid or the data violates the chosen mode.

ParamTypeDescription
bytes\KDuma\BinaryTools\BinaryStringData to write.
length?KDuma\BinaryTools\IntType (optional)Integer type describing the length field when using length mode.
terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Mandatory terminator sequence.
optional_terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Optional terminator sequence (currently emits a notice and behaves like $terminator).
padding\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Single-byte padding value for fixed-width fields.
padding_size?int (optional)Total field width when padding is enabled.

Returns: self


writeInt(...)
\KDuma\BinaryTools\BinaryWriter::writeInt(
    \KDuma\BinaryTools\IntType $type,
    int $value
): self

Serialises an integer according to the provided {@see IntType} definition.

Throws: \RuntimeException When the type is unsupported on this platform.

Throws: \InvalidArgumentException When the value lies outside the type's range.

ParamTypeDescription
type\KDuma\BinaryTools\IntTypeInteger description covering width, signedness, and byte order.
valueintValue to serialise.

Returns: self


writeString(...)
\KDuma\BinaryTools\BinaryWriter::writeString(
    \KDuma\BinaryTools\BinaryString $string
): self

Writes a UTF-8 validated string without terminator or padding.

Throws: \InvalidArgumentException When the data is not valid UTF-8.

ParamTypeDescription
string\KDuma\BinaryTools\BinaryStringUTF-8 string data to emit.

Returns: self


writeStringWith(...)
\KDuma\BinaryTools\BinaryWriter::writeStringWith(
    \KDuma\BinaryTools\BinaryString $string,
    ?\KDuma\BinaryTools\IntType $length = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $optional_terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $padding = null,
    ?int $padding_size = null
): self

Writes a UTF-8 string using one of the variable-length strategies.

Throws: \InvalidArgumentException When configuration is invalid or the string is not UTF-8.

ParamTypeDescription
string\KDuma\BinaryTools\BinaryStringUTF-8 string data to emit.
length?KDuma\BinaryTools\IntType (optional)Integer type describing the length field when using length mode.
terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Mandatory terminator sequence.
optional_terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Optional terminator sequence (currently emits a notice and behaves like $terminator).
padding\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Single-byte padding value for fixed-width fields.
padding_size?int (optional)Total field width when padding is enabled.

Returns: self


writeUint16BE(...)
\KDuma\BinaryTools\BinaryWriter::writeUint16BE(
    int $value
): self
ParamTypeDescription
valueintUnsigned 16-bit value.

Returns: self


writeBytesWithLength(...)
\KDuma\BinaryTools\BinaryWriter::writeBytesWithLength(
    \KDuma\BinaryTools\BinaryString $bytes,
    bool $use16BitLength = false
): self
ParamTypeDescription
bytes\KDuma\BinaryTools\BinaryStringPayload to write.
use16BitLengthbool (optional)When true, emits a 16-bit length; otherwise an 8-bit length.

Returns: self


writeStringWithLength(...)
\KDuma\BinaryTools\BinaryWriter::writeStringWithLength(
    \KDuma\BinaryTools\BinaryString $string,
    bool $use16BitLength = false
): self
ParamTypeDescription
string\KDuma\BinaryTools\BinaryStringUTF-8 string to write.
use16BitLengthbool (optional)When true, emits a 16-bit length; otherwise an 8-bit length.

Returns: self



BinaryReader

Namespace: KDuma\BinaryTools

Type: Final Class

Properties

$length

int $length

$data

KDuma\BinaryTools\BinaryString $data

$position

int $position

$remaining_bytes

int $remaining_bytes

$has_more_data

bool $has_more_data

$remaining_data

KDuma\BinaryTools\BinaryString $remaining_data

Methods

readByte()
\KDuma\BinaryTools\BinaryReader::readByte(): int

Reads the next byte from the stream.

Throws: RuntimeException When no more data is available.

Returns: int


readBytes(...)
\KDuma\BinaryTools\BinaryReader::readBytes(
    int $count
): \KDuma\BinaryTools\BinaryString

Reads exactly $count bytes from the current position.

Throws: RuntimeException When fewer than $count bytes remain.

ParamTypeDescription
countintNumber of bytes to read.

Returns: \KDuma\BinaryTools\BinaryString


readBytesWith(...)
\KDuma\BinaryTools\BinaryReader::readBytesWith(
    ?\KDuma\BinaryTools\IntType $length = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $optional_terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $padding = null,
    ?int $padding_size = null
): \KDuma\BinaryTools\BinaryString

Reads variable-length data using exactly one of the supplied strategies (length, terminator, optional terminator, or padding).

Throws: \InvalidArgumentException When mutually exclusive modes are combined or configuration is invalid.

Throws: RuntimeException When the data violates the expectations of the chosen mode.

ParamTypeDescription
length?KDuma\BinaryTools\IntType (optional)Integer type that stores the byte length when using length mode.
terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Required terminator sequence when using terminator mode.
optional_terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Terminator sequence that may be absent (fully consumes buffer when missing).
padding\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Single-byte padding value used for fixed-width fields.
padding_size?int (optional)Total field width in bytes when padding is enabled.

Returns: \KDuma\BinaryTools\BinaryString


readInt(...)
\KDuma\BinaryTools\BinaryReader::readInt(
    \KDuma\BinaryTools\IntType $type
): int

Reads an integer using the provided {@see IntType} definition.

Throws: RuntimeException When the type is unsupported or the value cannot be represented.

ParamTypeDescription
type\KDuma\BinaryTools\IntTypeInteger description covering width, signedness, and byte order.

Returns: int


readString(...)
\KDuma\BinaryTools\BinaryReader::readString(
    int $length
): \KDuma\BinaryTools\BinaryString

Reads a fixed-length UTF-8 string.

Throws: RuntimeException When insufficient data remains or decoding fails.

ParamTypeDescription
lengthintNumber of bytes to consume.

Returns: \KDuma\BinaryTools\BinaryString


readStringWith(...)
\KDuma\BinaryTools\BinaryReader::readStringWith(
    ?\KDuma\BinaryTools\IntType $length = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $optional_terminator = null,
    \KDuma\BinaryTools\Terminator|\KDuma\BinaryTools\BinaryString|null $padding = null,
    ?int $padding_size = null
): \KDuma\BinaryTools\BinaryString

Reads a UTF-8 string using one of the variable-length strategies (length, terminator, optional terminator, or padding).

Throws: \InvalidArgumentException When configuration is invalid.

Throws: RuntimeException When decoding fails or the data violates mode rules.

ParamTypeDescription
length?KDuma\BinaryTools\IntType (optional)Integer type specifying the length field when using length mode.
terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Required terminator.
optional_terminator\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Optional terminator.
padding\KDuma\BinaryTools\Terminator|KDuma\BinaryTools\BinaryString|null (optional)Single-byte padding value for fixed-width fields.
padding_size?int (optional)Total field width when padding is enabled.

Returns: \KDuma\BinaryTools\BinaryString


peekByte()
\KDuma\BinaryTools\BinaryReader::peekByte(): int

Returns the next byte without advancing the read pointer.

Throws: RuntimeException When no more data remains.

Returns: int - int Unsigned byte value.


peekBytes(...)
\KDuma\BinaryTools\BinaryReader::peekBytes(
    int $count
): \KDuma\BinaryTools\BinaryString

Returns the next $count bytes without advancing the read pointer.

Throws: RuntimeException When fewer than $count bytes remain.

ParamTypeDescription
countintNumber of bytes to inspect.

Returns: \KDuma\BinaryTools\BinaryString


skip(...)
\KDuma\BinaryTools\BinaryReader::skip(
    int $count
): void

Advances the read pointer by $count bytes.

Throws: RuntimeException When insufficient data remains.

ParamTypeDescription
countintNumber of bytes to skip.

Returns: void


seek(...)
\KDuma\BinaryTools\BinaryReader::seek(
    int $position
): void

Moves the read pointer to an absolute offset inside the buffer.

Throws: RuntimeException When the target lies outside the buffer.

ParamTypeDescription
positionintZero-based offset to seek to.

Returns: void


readUint16BE()
\KDuma\BinaryTools\BinaryReader::readUint16BE(): int

Returns: int


readBytesWithLength(...)
\KDuma\BinaryTools\BinaryReader::readBytesWithLength(
    bool $use16BitLength = false
): \KDuma\BinaryTools\BinaryString
ParamTypeDescription
use16BitLengthbool (optional)When true, reads a 16-bit length; otherwise an 8-bit length.

Returns: \KDuma\BinaryTools\BinaryString


readStringWithLength(...)
\KDuma\BinaryTools\BinaryReader::readStringWithLength(
    bool $use16BitLength = false
): \KDuma\BinaryTools\BinaryString
ParamTypeDescription
use16BitLengthbool (optional)When true, reads a 16-bit length; otherwise an 8-bit length.

Returns: \KDuma\BinaryTools\BinaryString



Enums

IntType

Namespace: \KDuma\BinaryTools\IntType

MembersValueDescription
UINT8'UINT8'Unsigned 8-bit integer (0-255) - Single byte
INT8'INT8'Signed 8-bit integer (-128 to 127) - Single byte
UINT16'UINT16'Unsigned 16-bit integer (0-65535) - Big-endian byte order
INT16'INT16'Signed 16-bit integer (-32768 to 32767) - Big-endian byte order
UINT32'UINT32'Unsigned 32-bit integer (0-4294967295) - Big-endian byte order
INT32'INT32'Signed 32-bit integer (-2147483648 to 2147483647) - Big-endian byte order
UINT16_LE'UINT16_LE'Unsigned 16-bit integer (0-65535) - Little-endian byte order
INT16_LE'INT16_LE'Signed 16-bit integer (-32768 to 32767) - Little-endian byte order
UINT32_LE'UINT32_LE'Unsigned 32-bit integer (0-4294967295) - Little-endian byte order
INT32_LE'INT32_LE'Signed 32-bit integer (-2147483648 to 2147483647) - Little-endian byte order
UINT64'UINT64'Unsigned 64-bit integer - Big-endian byte order (platform dependent range)
INT64'INT64'Signed 64-bit integer - Big-endian byte order (platform dependent range)
UINT64_LE'UINT64_LE'Unsigned 64-bit integer - Little-endian byte order (platform dependent range)
INT64_LE'INT64_LE'Signed 64-bit integer - Little-endian byte order (platform dependent range)

Terminator

Namespace: \KDuma\BinaryTools\Terminator

MembersValueDescription
NUL'NUL'Null character (0x00) - Commonly used for C-style string termination
SOH'SOH'Start of Heading (0x01) - Indicates the start of a header block
STX'STX'Start of Text (0x02) - Marks the beginning of text data
ETX'ETX'End of Text (0x03) - Marks the end of text data
EOT'EOT'End of Transmission (0x04) - Indicates end of data transmission
ENQ'ENQ'Enquiry (0x05) - Request for response or status
ACK'ACK'Acknowledge (0x06) - Positive acknowledgment signal
BEL'BEL'Bell (0x07) - Audio alert or notification signal
BS'BS'Backspace (0x08) - Move cursor back one position
HT'HT'Horizontal Tab (0x09) - Move to next tab stop
LF'LF'Line Feed (0x0A) - Move to next line (Unix line ending)
VT'VT'Vertical Tab (0x0B) - Move to next vertical tab position
FF'FF'Form Feed (0x0C) - Start new page or clear screen
CR'CR'Carriage Return (0x0D) - Return to start of line (classic Mac line ending)
SO'SO'Shift Out (0x0E) - Switch to alternate character set
SI'SI'Shift In (0x0F) - Switch back to standard character set
DLE'DLE'Data Link Escape (0x10) - Escape sequence for data link protocols
DC1'DC1'Device Control 1 (0x11) - Also known as XON for flow control
DC2'DC2'Device Control 2 (0x12) - General device control
DC3'DC3'Device Control 3 (0x13) - Also known as XOFF for flow control
DC4'DC4'Device Control 4 (0x14) - General device control
NAK'NAK'Negative Acknowledge (0x15) - Error or rejection signal
SYN'SYN'Synchronous Idle (0x16) - Synchronization in data streams
ETB'ETB'End of Transmission Block (0x17) - End of data block marker
CAN'CAN'Cancel (0x18) - Cancel current operation
EM'EM'End of Medium (0x19) - End of storage medium
SUB'SUB'Substitute (0x1A) - Replacement for invalid character
ESC'ESC'Escape (0x1B) - Start of escape sequence
FS'FS'File Separator (0x1C) - Delimiter between files
GS'GS'Group Separator (0x1D) - Delimiter between groups of data
RS'RS'Record Separator (0x1E) - Delimiter between records
US'US'Unit Separator (0x1F) - Delimiter between units of data
SP'SP'Space (0x20) - Standard whitespace character
CRLF'CRLF'Carriage Return + Line Feed (0x0D 0x0A) - Windows line ending