Open-Source PHP Framework - Designed for rapid development of performance-oriented scalable applications

/mvc/helpers/binary

[return to app]
1
<?php
/**
 * Converts ASCII-binary to text-strings and text to ASCII-binary strings
 * @author Eric David Benari
 * @link http://www.Vork.us/app/binary-converter
 * @license Creative Commons 3.0 - kindly retain this attribution (including link above)
 */
class binaryHelper {
    /**
     * Converts a string of binary bytes to text
     *
     * @param str $binary
     * @return str
     */
    public function bin2text($binary) {
        $bytes = preg_split('/\b/', $binary);
        foreach ($bytes as $byte) {
            $byte = trim($byte);
            if ($byte && is_numeric($byte)) {
                $str[] = chr(bindec($byte));
            }
        }
        return (isset($str) ? implode($str) : '');
    }

    /**
     * Converts a text string to a string of binary bytes representing the ASCII characters
     *
     * @param string $text
     * @param int $minBits Optional, default is 8-bit - set to 0 for dynamic-length bytes (note: ascii starts at
 
6-bits) * @return str */ public function text2bin($text, $minBits = 8) { $chars = str_split($text); foreach ($chars as $char) { $bytes[] = str_pad(decbin(ord($char)), $minBits, '0', STR_PAD_LEFT); } return (isset($bytes) ? implode(' ', $bytes) : ''); } }