PHP Classes

PHP Bit String: Manipulate strings of sequences of binary digits

Recommend this page to a friend!
  Info   View files Example   View files View files (5)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 102 All time: 9,737 This week: 145Up
Version License PHP version Categories
bitstring 1.0BSD License5.6PHP 5, Text processing, Data types
Description 

Author

This class can manipulate strings of sequences of binary digits.

It can take a string of data or binary digits and create an internal array of data.

The class can convert the bits to hexadecimal, to binary data, or a string of binary digits.

It also provide an iterator interface so it can be treated as an array of bits using the regular array manipulation functions.

Picture of Christian Vigh
  Performance   Level  
Name: Christian Vigh <contact>
Classes: 32 packages by
Country: France France
Age: 58
All time rank: 13810 in France France
Week rank: 7 Up1 in France France Up
Innovation award
Innovation award
Nominee: 20x

Winner: 3x

Example

<?php
   
/*************************************************************************************************

        This example demonstrates the use of the BitString and BitStringIterator classes on a
        simple example string, "ABCDEF", which will be considered as a string of bits.

     *************************************************************************************************/

   
require_once ( 'BitString.phpclass' ) ;

    if (
php_sapi_name ( ) != 'cli' )
        echo
'<pre>' ;

   
// getbits -
    // This function simply outputs bits from the specified value, up to $count.
   
function getbits ( $value, $count )
       {
       
$result = '' ;

        for (
$i = 0 ; $i < $count ; $i ++, $value >>= 1 )
           
$result .= ( $value & 1 ) ? '1' : '0' ;

        return (
$result ) ;
        }

   
// Our example string
   
$data = "ABCDEF" ;

   
// Create a bit string from it
   
$bs = new BitString ( $data ) ;

   
// Try the ToHex() and ToBin() functions. Note that ToBin (0) will print the bits in exactly the same order
    // as they are stored (least significant bit first), while ToBin(1) will print them in the order they are
    // printed by ToHex()
   
echo "ToHex() : " ; print_r ( $bs -> ToHex ( ) ) ; echo "\n" ;
    echo
"ToBin(1) : " ; print_r ( $bs -> ToBin ( 1 ) ) ; echo "\n" ;
    echo
"ToBin(0) : " ; print_r ( $bs -> ToBin ( 0 ) ) ; echo "\n" ;

   
// Use the ArrayAccess interface to retrieve and display each individual bit
   
echo "Bit per bit (for) : " ;

    for (
$i = 0 ; $i < count ( $bs ) ; $i ++ )
        echo
$bs [$i] ;

   
// Use the Iterator interface to display each individual bit
   
echo "\nBit per bit (foreach) : " ;

    foreach (
$bs as $bit )
        echo
$bit ;

   
// Now, use the BitString::GetBits() function to display bits by group of x bits, from 1 to 32.
    // Note that the getbits() function defined here will add trailing zeroes for bit counts that are
    // not a denominator of the machine's word size - this is not a bug, this inconvenience was aimed
    // at making this example simpler
   
for ( $bit_count = 1 ; $bit_count <= 32 ; $bit_count ++ )
       {
        echo
sprintf ( "\nTaking by %2d bits : ", $bit_count ) ;
       
        for (
$i = 0 ; $i < count ( $bs ) ; $i += $bit_count )
           {
           
$value = $bs -> GetBits ( $i, $bit_count ) ;

            if (
$value === false )
               
output ( "FALSE for offset $i, count $bit_count" ) ;

            echo
getbits ( $value, $bit_count ) ;
            }
        }

   
// Now use a BitStringIterator object : extract bits from the bit string by groups of
    // 3 components having 8 bits each. It should display the hexadecimal translation of
    // "ABCDEF" which is : "414243444546"
   
echo "\nBitStringIterator(8,3) : " ;

    foreach ( new
BitStringIterator ( $bs, 8, 3 ) as $values )
       {
        foreach (
$values as $value )
            echo (
sprintf ( "%02X", $value ) ) ;
        }


Details

INTRODUCTION

This package introduces two classes : BitString and BitStringIterator.

A bit string can take as input a string or another bit string. The least significant bit in the string will be the least significant bit of the first byte of the string ; the most significant bit will be the most significant bit of the last byte of the string.

This may seem counter-natural, as we would expect the reverse situation. However, the string is internally converted to an array of little-endian integers (4 bytes on 32 bits systems, 8 bytes on 64-bits ones).

The original intent of this class was to retrieve color values from a stream of bytes ; each color having a number of bits per components, and a number of components per color (for example, 24-bits RGB colors have a number of bits per components of 8, and a number of components per color of 3, one for each of the red, green, blue components).

Anyway, it can be used to retrieve any portion of bits within a bit string using the BitString::GetBits method. The BitStringIterator class has been designed to retrieve things like colors values, but can be used for other purposes.

LIMITATIONS

These classes have been designed with performance in mind ; for this reason, no more than 32 bits can be retrieved at once by the GetBits() method on 32-bits platforms, and no more than 64 on 64-bits platforms. This is not a design issue, but rather a design choice.

MORE TO COME

In its current state, the BitString class acts as a read-only class : it only extracts bits from a bit string flow.

More features will be added in the future, such as setting bits or performing bitwise operations with other bit strings.

REFERENCE

BitString class

Methods

Constructor

$bitstring	=  new BitString ( $data, $data_size_in_bits = false, $filler = 0 ) ;

Creates a bit string based on the supplied string data. The data can be later accessed through one of the following methods :

  • By calling the GetBits() method to retrieve a group of bits
  • By using the array access operator to retrieve an individual bit
  • By using the iterator interface to retrieve individual bits

The parameters are the following :

  • $data (string or BitString) : Data to be used to build the BitString. It can either be : - A string, which will be converted to integer values of size PHP\_INT_\SIZE, in little-endian order. - An existing BitString object, which will be duplicated.
  • $data\_size\_in\_bits (integer) : If not specified, the total number of bits will be the length of $data 8. If specified, indicates the exact number of bits to consider ;$datawill be truncated if this parameter is shorter thatstrlen($data)*, and expanded with the filler value if greater.
  • $filler (byte) : Filler value, for unset bits, specified as a byte. This value is used when the total number of bits does not fit on a byte boundary, or when $data needs to be expanded because $data\_size\_in\_bits is greater than strlen($data) 8. A value offalse,null* or empty string will be interpreted as 0x00.

GetBits

public function  GetBits ( $offset, $bit_count )

Returns $bit\_count bits starting at the specified offset in the BitString.

Interfaces

Countable

The count() function, when applied to a BitString object, will return the actual number of bits.

ArrayAccess

Allows to access a BitString object as an array, and retrieve each bit. The following example prints out all the bits in a BitString :

$bs 	=  new BiString ( "ABCDEF" ) ;

for  ( $i = 0 ; $i  <  count ( $bs ) ; $i ++ )
	echo $bs [$i] ;

Iterator

Allows to loop through each bit of a BiString object using a foreach() construct. The following example prints out all the bits in a BitString :

$bs 	=  new BiString ( "ABCDEF" ) ;

foreach  ( $bs  as  $bit )
	echo $bit ;

BitStringIterator class

Allows to iterate through a BitString object and retrieve groups of bits as array.

This class was originally implemented to read a stream of values representing colors, with a specific number of bits per color component, and a number of components per color, but it can be used for many other purposes.

Constructor

$iterator	=  new BitStringIterator ( $data, $bits_per_component, $component_count = 1 ) ;

The BitStringIterator class allows to iterate through a BitString by groups of $bits\_per\_component bits.

An array of $component\_count elements will be returned upon each iteration.

The parameters are the following :

  • $data (string or BitString) : BitString to be iterated. If a simple string is specified, it will be internally converted to a BitString object.
  • $bits\_per\_component (integer) : Number of bits per component.

$component\_count (integer) : Number of components having $bits\_per\_component bits to be returned upon each iteration.


  Files folder image Files  
File Role Description
Plain text file BitString.phpclass Class Class source
Accessible without login Plain text file example.php Example Example script
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file NOTICE Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

 Version Control Unique User Downloads Download Rankings  
 100%
Total:102
This week:0
All time:9,737
This week:145Up