-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathBHDConverter.php
90 lines (78 loc) · 2.21 KB
/
BHDConverter.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
namespace axios\tools;
class BHDConverter
{
private $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // len:62
private $patch = '0';
public function __construct($dict = null, $patch = null)
{
if ($dict) {
$this->dict = $dict;
}
if ($patch) {
$this->patch = $patch;
}
}
/**
* @param int|string $num_str
* @param int $from number system
* @param int $to number system
* @param int $min_length default 0
*/
public function anyToAny($num_str, int $from, int $to, int $min_length = 0): string
{
if (!\is_string($num_str)) {
$num_str = (string) $num_str;
}
if (10 !== $from) {
$fromBase = $this->anyToDecimal($num_str, $from);
} else {
$fromBase = $num_str;
}
$result = $this->decimalToAny($fromBase, $to);
if (0 !== $min_length) {
$strLength = \strlen($result);
while ($strLength < $min_length) {
$result = $this->patch . $result;
++$strLength;
}
}
return $result;
}
/**
* @param int|string $num
* @param int $from number_system : 10(Decimal) | 16(Hex) | 62(62 binary)
*
* @return int|string
*/
public function anyToDecimal($num, int $from)
{
$num = (string) $num;
$from = (string) $from;
$dict = $this->dict;
$len = \strlen($num);
$dec = '0';
for ($i = 0; $i < $len; ++$i) {
$pos = strpos($dict, $num[$i]);
$dec = bcadd(bcmul(bcpow($from, (string) ($len - $i - 1)), (string) $pos), $dec);
}
return $dec;
}
/**
* @param int|string $num
* @param int $to number_system
*/
public function decimalToAny($num, int $to): string
{
$num = (string) $num;
$to = (string) $to;
$dict = $this->dict;
$ret = '';
do {
$ret = $dict[bcmod($num, $to)] . $ret;
$num = bcdiv($num, $to);
} while ($num > 0);
return $ret;
}
}