/
BcmathEncoder.php
48 lines (42 loc) · 1.25 KB
/
BcmathEncoder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
/*
* This file is part of the Base62 package
*
* Copyright (c) 2011 Anthony Ferrara
* Copyright (c) 2016-2018 Mika Tuupola
*
* Based on BaseConverter by Anthony Ferrara
* https://github.com/ircmaxell/SecurityLib/tree/master/lib/SecurityLib
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/base62
*
*/
namespace Tuupola\Base62;
use Tuupola\Base62;
class BcmathEncoder extends BaseEncoder
{
/* http://codegolf.stackexchange.com/a/21672 */
public function baseConvert(array $source, $source_base, $target_base)
{
$result = [];
while ($count = count($source)) {
$quotient = [];
$remainder = 0;
for ($i = 0; $i !== $count; $i++) {
$accumulator = bcadd($source[$i], bcmul($remainder, $source_base));
$digit = bcdiv($accumulator, $target_base, 0);
$remainder = bcmod($accumulator, $target_base);
if (count($quotient) || $digit) {
array_push($quotient, $digit);
};
}
array_unshift($result, $remainder);
$source = $quotient;
}
return $result;
}
}