forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OctalToDecimal.php
56 lines (48 loc) · 1.2 KB
/
OctalToDecimal.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
<?php
/**
* This function converts the
* submitted Octal Number to
* Decimal Number.
*
* Working of Algorithm
* (10) base 8
* (1 * (8 ^ 1) + 0 * (8 ^ 0)) base 10
* (8 + 0) base 10
* 9 base 10
* @param string $octalNumber
* @return int
* @throws \Exception
*/
function octalToDecimal($octalNumber)
{
if (!is_numeric($octalNumber)) {
throw new \Exception('Please pass a valid Octal Number for Converting it to a Decimal Number.');
}
$decimalNumber = 0;
$octalDigits = array_reverse(str_split($octalNumber));
foreach ($octalDigits as $index => $digit) {
$decimalNumber += $digit * pow(8, $index);
}
return $decimalNumber;
}
/**
* This function converts the
* submitted Decimal Number to
* Octal Number.
*
* @param string $decimalNumber
* @return string
* @throws \Exception
*/
function decimalToOctal($decimalNumber)
{
if (!is_numeric($decimalNumber)) {
throw new \Exception('Please pass a valid Decimal Number for Converting it to an Octal Number.');
}
$octalNumber = '';
while ($decimalNumber > 0) {
$octalNumber = ($decimalNumber % 8) . $octalNumber;
$decimalNumber /= 8;
}
return $octalNumber;
}