Toolbox for working with binary and hex data. Similar to NodeJS Buffer.

v0.4.1 2017-06-21 18:23 UTC


============= This library provides a Buffer and Parser class to make dealing with binary data in PHP easier. Templates extend this by offering a read/write interface for larger serialized structures.

Build Status Code Coverage Scrutinizer Code Quality Latest Stable Version Join the chat at


  • PHP 5.6+
  • Composer
  • ext-gmp


You can install this library via Composer: composer require bitwasp/buffertools


Buffer's are immutable classes to store binary data. BufferHex will convert the provided data to binary, as will BufferInt. Buffer's main methods are:

  • getBinary()
  • getHex()
  • getInt()

Parser will read Buffers. Parser's main methods are:

  • readBytes()
  • getArray()
  • getVarInt()
  • getString()
  • writeBytes()

In most cases, the interface offered by Parser should not be used directly. Instead, Templates expose read/write access to larger serialized structures.

Using Parser to read binary data

    use BitWasp\Buffertools\Buffer;
    use BitWasp\Buffertools\Parser;
    // Parsers read Buffers
    $buffer = new Buffer('abc');
    $parser = new Parser($buffer);
    // Call readBytes to unpack the data
    /** @var Buffer[] $set */
    $set = [
    foreach ($set as $item) {
        echo $item->getBinary() . PHP_EOL;

Using Templates

use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\Parser;
use BitWasp\Buffertools\TemplateFactory;

$structure = (object) [
    'hash' => hash('sha256', 'abc'),
    'message_id' => 9123,
    'message' => "Hi there! What's up?"

// Templates are read/write
$template = (new TemplateFactory)

// Write the structure
$binary = $template->write([
    new Buffer($structure->message)

echo $binary->getHex() . "\n";

// Use the template to read resulting Buffer
$parsed = $template->parse(new Parser($binary));

$p = (object) [
    'hash' => $parsed[0]->getHex(),
    'message_id' => $parsed[1],
    'message' => $parsed[2]->getBinary()