Location: PHPKode > scripts > Variable Length Coding > variable-length-coding/vlc.class.php
<?php

/**
 * Variable Length Coding Writer class
 * 
 * @author Robin Schuil <hide@address.com>
 * @version 1.0.0
 *
 */
class VLCWriter {

	var $data = array();
	var $odd = false;
	var $offset = 0;
	
	/**
	 * Constructor
	 *
	 * @return VLCWriter
	 */
	function VLCWriter() {
		
	}

	/**
	 * Append a 4-bit nibble
	 *
	 * @param int $nibble
	 */
	function putNibble( $nibble ) {
		if( $this->odd ) {
			$this->odd = false;
			$this->data[$this->offset] |= $nibble;
			$this->offset++;
		}
		else {
			$this->odd = true;
			$this->data[$this->offset] = $nibble << 4;
		}
	}
	
	/**
	 * Encode an integer value
	 *
	 * @param int $uValue
	 */
	function zipInt( $uValue ) {
		do {
			$b = $uValue & 0x07;
			$uValue >>= 3;
			if( $uValue ) {
				$b |= 0x08;
			}
			$this->putNibble( $b );
		} while( $uValue );
	}
	
	/**
	 * Return the result as a binary string
	 *
	 * @return string
	 */
	function toString() {
		$array = $this->data;
		array_unshift( $array, 'C*' );
		return call_user_func_array( 'pack', $array );
	}

}

class VLCReader {
	
	var $data = array();
	var $odd = false;
	var $offset = 0;
	
	/**
	 * Constructor
	 *
	 * @param string $data
	 * @return VLCReader
	 */
	function VLCReader( $data ) {
		$this->fromString( $data );
	}
	
	/**
	 * Convert a binary string to an array of bytes
	 *
	 * @param string $data
	 */
	function fromString( $data ) {
		$result = unpack( 'C*', $data );
		$this->data = array_values( $result );
	}
	
	/**
	 * Read next 4-bit nibble
	 *
	 * @return int
	 */
	function getNibble() {
		if( $this->odd ) {
			$this->odd = false;
			return( $this->data[ $this->offset++ ] & 0x0f );
		}
		else {
			$this->odd = true;
			return( $this->data[ $this->offset ] >> 4 );
		}
	}
	
	/**
	 * Decode next integer
	 *
	 * @return int
	 */
	function unzipInt() {
		$offset = 0;
		$b = 0;
		$v = 0;
		do {
			$b = $this->getNibble();
			$v += ( ( $b & 0x07 ) << $offset );
			$offset += 3;
		} while( $b & 0x08 );
		return $v;
	}
	
}

?>
Return current item: Variable Length Coding