4 * A Utility class for converting between raw binary strings and a given
9 * @category PHPCryptLib
11 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
12 * @copyright 2011 The Authors
13 * @license http://www.opensource.org/licenses/mit-license.html MIT License
14 * @version Build @@version@@
17 namespace CryptLib\Core
;
20 * A Utility class for converting between raw binary strings and a given
23 * @category PHPCryptLib
25 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
30 * Convert from a raw binary string to a string of characters
32 * @param string $string The string to convert from
33 * @param string $characters The list of characters to convert to
35 * @return string The converted string
37 public static function convertFromBinary($string, $characters) {
38 if ($string === '' ||
empty($characters)) {
41 $string = str_split($string);
42 $callback = function($str) {
45 $string = array_map($callback, $string);
46 $converted = static::baseConvert($string, 256, strlen($characters));
47 $callback = function ($num) use ($characters) {
48 return $characters[$num];
50 $ret = implode('', array_map($callback, $converted));
55 * Convert to a raw binary string from a string of characters
57 * @param string $string The string to convert from
58 * @param string $characters The list of characters to convert to
60 * @return string The converted string
62 public static function convertToBinary($string, $characters) {
63 if (empty($string) ||
empty($characters)) {
66 $string = str_split($string);
67 $callback = function($str) use ($characters) {
68 return strpos($characters, $str);
70 $string = array_map($callback, $string);
71 $converted = static::baseConvert($string, strlen($characters), 256);
72 $callback = function ($num) {
75 return implode('', array_map($callback, $converted));
79 * Convert an array of input blocks to another numeric base
81 * This function was modified from an implementation found on StackOverflow.
82 * Special Thanks to @KeithRandall for supplying the implementation.
84 * @param int[] $source The source number, as an array
85 * @param int $srcBase The source base as an integer
86 * @param int $dstBase The destination base as an integer
88 * @see http://codegolf.stackexchange.com/questions/1620/arb/1626#1626
89 * @return int[] An array of integers in the encoded base
91 public static function baseConvert(array $source, $srcBase, $dstBase) {
93 $message = sprintf('Invalid Destination Base: %d', $dstBase);
94 throw new \
InvalidArgumentException($message);
97 $count = count($source);
100 $remainder = $count = $i = 0;
102 $dividend = $source[$i++
] +
$remainder * $srcBase;
103 $remainder = $dividend %
$dstBase;
104 $res = ($dividend - $remainder) / $dstBase;
105 if ($count ||
$res) {
106 $source[$count++
] = $res;
109 $result[] = $remainder;
111 return array_reverse($result);