/mvc/helpers/binary
[return to app]1
<?php
2 /**
3 * Converts ASCII-binary to text-strings and text to ASCII-binary strings
4 * @author Eric David Benari
5 * @link http://www.Vork.us/app/binary-converter
6 * @license Creative Commons 3.0 - kindly retain this attribution (including link above)
7 */
8 class binaryHelper {
9 /**
10 * Converts a string of binary bytes to text
11 *
12 * @param str $binary
13 * @return str
14 */
15 public function bin2text($binary) {
16 $bytes = preg_split('/\b/', $binary);
17 foreach ($bytes as $byte) {
18 $byte = trim($byte);
19 if ($byte && is_numeric($byte)) {
20 $str[] = chr(bindec($byte));
21 }
22 }
23 return (isset($str) ? implode($str) : '');
24 }
25
26 /**
27 * Converts a text string to a string of binary bytes representing the ASCII characters
28 *
29 * @param string $text
30 * @param int $minBits Optional, default is 8-bit - set to 0 for dynamic-length bytes (note: ascii starts at
6-bits)
31 * @return str
32 */
33 public function text2bin($text, $minBits = 8) {
34 $chars = str_split($text);
35 foreach ($chars as $char) {
36 $bytes[] = str_pad(decbin(ord($char)), $minBits, '0', STR_PAD_LEFT);
37 }
38 return (isset($bytes) ? implode(' ', $bytes) : '');
39 }
40 }