PHPackages                             tianhe1986/fatbinarybuffer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tianhe1986/fatbinarybuffer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tianhe1986/fatbinarybuffer
==========================

binary buffer read and write

1.1.1(5y ago)02.9k1MITPHPPHP ^7.0CI failing

Since Nov 2Pushed 4y ago1 watchersCompare

[ Source](https://github.com/tianhe1986/FatBinaryBuffer)[ Packagist](https://packagist.org/packages/tianhe1986/fatbinarybuffer)[ Docs](https://github.com/tianhe1986/FatBinaryBuffer)[ RSS](/packages/tianhe1986-fatbinarybuffer/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

FatBinaryBuffer
===============

[](#fatbinarybuffer)

FatBinaryBuffer is a lightweight library for reading/writing binary string.

Requires
========

[](#requires)

PHP 7.0 or higher

Installation
============

[](#installation)

```
 composer require tianhe1986/fatbinarybuffer

```

and then in your code

```
require_once __DIR__ . '/vendor/autoload.php';
use FatBinaryBuffer\FatBinaryBuffer;

```

Support
=======

[](#support)

It supports char/unsigned char, short/unsigned short, int32/uint32, int64/uint64, string, string with length.
**Do not support float and double!**

Usage
=====

[](#usage)

### big endian vs little endian

[](#big-endian-vs-little-endian)

```
$binaryBufferBE = new FatBinaryBuffer(true); //big endian
$binaryBufferLE = new FatBinaryBuffer(false); //little endian

```

### buffer opration

[](#buffer-opration)

```
$binaryBuffer = new FatBinaryBuffer();

//set buffer, would calculate length and offset automaticly
$buffer = base64_decode('XXXXXX');
$binaryBuffer->setBuffer($buffer);

//get buffer
$buffer = $binaryBuffer->getBuffer();

// clear buffer
$binaryBuffer->clear();

// set offset, and then continue to read/write from this position, take byte as unit
$binaryBuffer->setOffset(4); // read/write from the 4th byte

// rewind, just set offset 0
$binaryBuffer->rewind();

```

### writing data

[](#writing-data)

```
$binaryBuffer = new FatBinaryBuffer(true);

// char and unsigned char, must pass a number, not a char, or you can use `ord` function for transformation
$binaryBuffer->writeChar(100);
$binaryBuffer->writeUChar(225);

// short and unsigned short
$binaryBuffer->writeShort(-1234);
$binaryBuffer->writeUShort(1236);

// int32 and uint32
$binaryBuffer->writeInt32(-999);
$binaryBuffer->writeUInt32(1098);

// int64 and uint64
$binaryBuffer->writeInt64(-98765);
$binaryBuffer->writeUInt64(888);

// string, write its length as a uint32 value first, and then the real string
$binaryBuffer->writeString("张学友！张学友！我们爱你！");

// string with given length, padding with NUL
$binaryBuffer->writeStringByLength("Hello world", 3); // would get 'Hel' when reading

```

### reading data

[](#reading-data)

```
$newBuffer = new FatBinaryBuffer();
$newBuffer->setBuffer($binaryBuffer->getBuffer());

// char and unsigned char
$char = $newBuffer->readChar();
$uchar = $newBuffer->readUChar();

// short and unsigned short
$short = $newBuffer->readShort();
$ushort = $newBuffer->readUShort();

// int32 and uint32
$a = $newBuffer->readInt32();
$b = $newBuffer->readUInt32();

// int64 and uint64
$a = $newBuffer->readInt64();
$b = $newBuffer->readUInt64();

// string, read its length first, and then the real string
$str = $newBuffer->readString();

// read string with given length, would remove NUL at the end of the string
$str = $newBuffer->readStringByLength(3);

```

### writing/reading with endian (version &gt;= 1.1)

[](#writingreading-with-endian-version--11)

From 1.1, short/ushort/int32/uint32/int64/uint64 cound handle with giving endian.

```
//whatever initial endian
$binaryBuffer = new FatBinaryBuffer((mt_rand(1, 10) % 2) === 0);

//write with big endian
$binaryBuffer->writeShort(-1234, true);

//write with little endian
$binaryBuffer->writeUShort(1236, false);

//read with big endian
$binaryBuffer->readInt32(true);

//read with little endian
$binaryBuffer->readUInt64(false);

```

### combine with websocket server

[](#combine-with-websocket-server)

Taking [Workerman](https://github.com/walkor/workerman) for exmaple.

```
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
use Workerman\Protocols\Websocket;
use FatBinaryBuffer\FatBinaryBuffer;

$ws_worker = new Worker("websocket://0.0.0.0:13001");

// 4 processes
$ws_worker->count = 4;

$ws_worker->onConnect = function($connection)
{
    $connection->onWebSocketConnect = function($connection , $http_header)
    {
        $connection->websocketType = Websocket::BINARY_TYPE_ARRAYBUFFER;
    };
};

$ws_worker->onMessage = function($connection, $data)
{
    $socketData = new FatBinaryBuffer(false);
    $socketData->setBuffer($data);
    $opcode = $socketData->readUInt32();
    echo $opcode."\n";
    echo $socketData->readUInt32()."\n";
    echo $socketData->readUInt32()."\n";
    if ($opcode === 21102) {
        echo $socketData->readUInt32()."\n";
        $newData = new FatBinaryBuffer(false);
        $newData->writeUInt32(21103);
        $newData->writeUInt32(16);
        $newData->writeUInt32(11);
        $newData->writeUInt32(777);
        $connection->send($newData->getBuffer());
    } else if ($opcode === 21104) {
        $len = $socketData->readUShort();
        echo "string len ".$len."\n";
        echo $socketData->readStringByLength($len)."\n";
        echo $socketData->readChar()."\n";
        echo $socketData->readUShort()."\n";
        echo $socketData->readInt32()."\n";
        echo $socketData->readStringByLength(5)."\n";
    }
};
Worker::runAll();

```

Using [Layabox](https://www.layabox.com/) as a typescript client for testing. It works fine.

```
import Socket = Laya.Socket;
import Byte = Laya.Byte;

class TestSocket {
    private socket: Socket;
    private output: Byte;
    private byte: Byte;
    private headerLength:number = 12;

    constructor() {
        this.byte = new Byte();
        this.byte.endian = Byte.LITTLE_ENDIAN;
        this.connect();
    }

    private connect(): void {
        this.socket = new Socket();
        this.socket.connectByUrl("ws://localhost:13001");

        this.output = this.socket.output;

        this.socket.on(Laya.Event.OPEN, this, this.onSocketOpen);
        this.socket.on(Laya.Event.CLOSE, this, this.onSocketClose);
        this.socket.on(Laya.Event.MESSAGE, this, this.onMessageReveived);
        this.socket.on(Laya.Event.ERROR, this, this.onConnectError);
    }

    private onSocketOpen(): void {
        console.log("Connected");

        this.byte.clear();
        this.byte.writeUint32(21102);
        this.byte.writeUint32(16);
        this.byte.writeUint32(657);
        this.byte.writeUint32(10);

        this.socket.send(this.byte.buffer);
        this.byte.clear();
    }

    private onSocketClose(): void {
        console.log("Socket closed");
    }

    private onMessageReveived(message: any): void {
        console.log("Message from server:");
        if (typeof message == "string") {
            console.log(message);
        }
        else if (message instanceof ArrayBuffer) {
            let byte = new Byte(message);
            let messageId = byte.getUint32();
			let messageLength = byte.getUint32() - this.headerLength;
			let userId = byte.getUint32();

			console.log(messageId, messageLength, userId);
            this.handleMessage(byte, messageId);
        }
        this.socket.input.clear();
    }

    private onConnectError(e: Event): void {
        console.log("error");
    }

    protected handleMessage(byte:Byte, messageId:number):void
    {
        if (messageId === 21103) {
            let serverTime:number = byte.getUint32();
            console.log("recieve heart beat " + serverTime);

            this.byte.clear();
            let str = "You are shock!我爱黎明！！！";
            let newByte = new Byte();
            newByte.writeUTFString(str);
            newByte.writeByte(111);
            newByte.writeUint16(65500);
            newByte.writeInt32(-70);
            newByte.writeUTFBytes("topod");

            let len = this.headerLength + newByte.length;
            this.byte.writeUint32(21104);
            this.byte.writeUint32(len);
            this.byte.writeUint32(657);
            this.byte.writeArrayBuffer(newByte.buffer);

            this.socket.send(this.byte.buffer);
            this.byte.clear();
        }
    }
}

```

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~891 days

Total

2

Last Release

1860d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/640ea2d81be289342282579fb6436637ee991681f076c2e3f0a710fa231da6fe?d=identicon)[tianhe1986](/maintainers/tianhe1986)

---

Top Contributors

[![tianhe1986](https://avatars.githubusercontent.com/u/19562319?v=4)](https://github.com/tianhe1986 "tianhe1986 (23 commits)")[![fidovo](https://avatars.githubusercontent.com/u/4673494?v=4)](https://github.com/fidovo "fidovo (3 commits)")

---

Tags

stringreadwritebinaryBuffer

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tianhe1986-fatbinarybuffer/health.svg)

```
[![Health](https://phpackages.com/badges/tianhe1986-fatbinarybuffer/health.svg)](https://phpackages.com/packages/tianhe1986-fatbinarybuffer)
```

###  Alternatives

[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k394.3M1.5k](/packages/nette-utils)[coduo/php-to-string

Simple library that converts PHP value into strings

27112.7M10](/packages/coduo-php-to-string)[opis/string

Multibyte strings as objects

7120.9M7](/packages/opis-string)[icecave/repr

A library for generating string representations of any value, inspired by Python's reprlib library.

277.1M4](/packages/icecave-repr)[phootwork/lang

Missing PHP language constructs

1224.8M8](/packages/phootwork-lang)[phpinnacle/buffer

PHPinnacle binary buffer implementation

2493.7k10](/packages/phpinnacle-buffer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
