PHPackages                             guillaumetissier/bit-string - 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. guillaumetissier/bit-string

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

guillaumetissier/bit-string
===========================

A PHP library for manipulating bit strings and converting them to various representations

v1.5.0(2mo ago)0121MITPHPPHP &gt;=8.1

Since Feb 2Pushed 2mo agoCompare

[ Source](https://github.com/guillaumetissier/bit-string)[ Packagist](https://packagist.org/packages/guillaumetissier/bit-string)[ RSS](/packages/guillaumetissier-bit-string/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (8)Used By (1)

BitString
=========

[](#bitstring)

A PHP library for manipulating bit strings with both mutable and immutable implementations.

Features
--------

[](#features)

- **Two implementations**: Mutable (`BitString`) and Immutable (`BitStringImmutable`)
- **Flexible conversion system**: Pluggable converters for different formats
- **Bitwise operations**: AND, OR, XOR, NOT, shifts, rotations
- **Type-safe**: Full type hints and strict typing
- **Well-tested**: Comprehensive test suite

Installation
------------

[](#installation)

```
composer require guillaumetissier/bit-string
```

Usage
-----

[](#usage)

### Creating BitStrings

[](#creating-bitstrings)

```
use BitString\BitString;
use BitString\BitStringImmutable;

// From binary string
$mutable = BitString::fromString('10110101');
$immutable = BitStringImmutable::fromString('10110101');

// Factory methods
$empty = BitSt:empty();                 // ''
$zeros = BitString::zeros(8);           // '00000000'
$ones = BitStringImmutable::ones(8);    // '11111111'
```

### Using Converters

[](#using-converters)

```
use BitString\Converter\BinaryConverter;
use BitString\Converter\HexConverter;
use BitString\Converter\DecimalConverter;
use BitString\Converter\CodewordConverter;

// Binary - returns mutable by default
$binConverter = new BinaryConverter();
$bits = $binConverter->toBitString('10110101');              // BitString (mutable)
$immutable = $binConverter->toBitStringImmutable('10110101'); // BitStringImmutable
$binary = $binConverter->fromBitString($bits);                // '10110101'

// Hexadecimal
$hexConverter = new HexConverter();
$bits = $hexConverter->toBitString('B5');                     // BitString (mutable)
$immutable = $hexConverter->toBitStringImmutable('B5');       // BitStringImmutable
$hex = $hexConverter->fromBitString($bits);                   // 'B5'

// With prefix
$hexConverter->withPrefix(true);
$hex = $hexConverter->fromBitString($bits);                   // '0xB5'

// Decimal
$decConverter = new DecimalConverter();
$bits = $decConverter->toBitString(181);                      // BitString (mutable)
$immutable = $decConverter->toBitStringImmutable(181);        // BitStringImmutable
$decimal = $decConverter->fromBitString($bits);               // 181

// With fixed width
$decConverter->withWidth(8);
$bits = $decConverter->toBitString(5);                        // '00000101'

// Codewords
$cwConverter = new CodewordConverter();
$cwConverter->withWordLength(4);
$bits = $cwConverter->toBitString(['1011', '0101']);          // BitString (mutable)
$immutable = $cwConverter->toBitStringImmutable(['1011', '0101']); // BitStringImmutable
$codewords = $cwConverter->fromBitString($bits);              // ['1011', '0101']
```

### Mutable vs Immutable

[](#mutable-vs-immutable)

```
// Mutable - modifies in place
$mutable = BitString::fromString('1100');
$mutable->not();                        // Mutates instance
echo $mutable->toString();              // '0011'

// Immutable - returns new instance
$immutable = BitStringImmutable::fromString('1100');
$result = $immutable->not();            // Returns new instance
echo $immutable->toString();            // '1100' (unchanged)
echo $result->toString();               // '0011' (new instance)

// Chaining with mutable
$bits = BitString::fromString('11')
    ->prepend(BitString::fromString('00'))
    ->append(BitString::fromString('11'))
    ->not();                            // All operations mutate
echo $bits->toString();                 // '110000'

// Chaining with immutable
$result = BitStringImmutable::fromString('11')
    ->prepend(BitStringImmutable::fromString('00'))
    ->append(BitStringImmutable::fromString('11'))
    ->not();                            // All operations return new instances
```

### Bitwise Operations

[](#bitwise-operations)

```
$a = BitString::fromString('1100');
$b = BitString::fromString('1010');

$a->and($b);        // '1000' (mutates $a)
$a->or($b);         // '1110' (mutates $a)
$a->xor($b);        // '0110' (mutates $a)
$a->not();          // '0011' (mutates $a)
```

### Bit Manipulation

[](#bit-manipulation)

```
$bits = BitString::fromString('1011');

// Access
$bit = $bits->get(0);                   // 1
$length = $bits->length();              // 4
$count = $bits->bitCount();             // 4 (alias)
$ones = $bits->popCount();              // 3

// Modify (mutable)
$bits->set(1, 1);                       // Mutates: '1111'
$bits->flip(0);                         // Mutates: '0111'

// Concatenate
$bits->prepend(BitString::fromString('00'));  // Mutates: '000111'
$bits->append(BitString::fromString('11'));   // Mutates: '00011111'
```

### Shifts and Rotations

[](#shifts-and-rotations)

```
$bits = BitString::fromString('10110101');

$bits->shiftLeft(2);        // '11010100'
$bits->shiftRight(2);       // '00101101'
$bits->rotateLeft(2);       // '11010110'
$bits->rotateRight(2);      // '01101101'
```

### Extraction

[](#extraction)

```
$bits = BitString::fromString('10110101');

// Extract N bits from a position
$bits->extract(2, 4);                   // '1101'

// Slice an interval [start, end)
$bits->slice(2, 6);                     // '1101'

// First / last N bits
$bits->first(3);                        // '101'
$bits->last(3);                         // '101'

// Single codeword at index
$bits->codeword(0, 4);                  // '1011'
$bits->codeword(1, 4);                  // '0101'

// Extraction is composable — extract then split
$bits->slice(2, 6)->first(2);           // '11'
```

All extraction methods return the same type as the source (`BitString` or `BitStringImmutable`), and work identically on both implementations.

When to Use Mutable vs Immutable
--------------------------------

[](#when-to-use-mutable-vs-immutable)

**Use `BitString` (mutable) when:**

- You need to modify bits in loops (better performance)
- Working with large bit strings that change frequently
- Building bit strings incrementally
- Performance is critical

**Use `BitStringImmutable` when:**

- Thread safety is important
- You want to avoid side effects
- Working with functional programming patterns
- The bit string represents a value that shouldn't change

Requirements
------------

[](#requirements)

- PHP 8.1 or higher

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

MIT License

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance82

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~1 days

Total

7

Last Release

89d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/295253ce7789fa9279c56ac58b2d42bd808f97bb7f312fa2c78e2e782a31cfaf?d=identicon)[guillaume.tissier](/maintainers/guillaume.tissier)

---

Top Contributors

[![guillaumetissier](https://avatars.githubusercontent.com/u/8750033?v=4)](https://github.com/guillaumetissier "guillaumetissier (9 commits)")

---

Tags

encodingbinarybitbitstringcodeword

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/guillaumetissier-bit-string/health.svg)

```
[![Health](https://phpackages.com/badges/guillaumetissier-bit-string/health.svg)](https://phpackages.com/packages/guillaumetissier-bit-string)
```

###  Alternatives

[paragonie/constant_time_encoding

Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)

901329.7M148](/packages/paragonie-constant-time-encoding)[alchemy/binary-driver

A set of tools to build binary drivers

19110.9M39](/packages/alchemy-binary-driver)[paquettg/string-encode

Facilitating the process of altering string encoding in PHP.

698.7M43](/packages/paquettg-string-encode)[comcast/php-legal-licenses

A utility to generate a Licenses file containing the full license text for every dependency in your project for legal purposes.

821.1M9](/packages/comcast-php-legal-licenses)[yaroslavche/bitmask

BitMask, EnumBitMask

3453.7k1](/packages/yaroslavche-bitmask)[onnov/detect-encoding

Text encoding definition class instead of mb\_detect\_encoding. Defines: utf-8, windows-1251, koi8-r, iso-8859-5, ibm866, .....

223.8M8](/packages/onnov-detect-encoding)

PHPackages © 2026

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