-
-
Notifications
You must be signed in to change notification settings - Fork 585
Expand file tree
/
Copy pathOctalToDecimal.php
More file actions
58 lines (49 loc) · 1.29 KB
/
Copy pathOctalToDecimal.php
File metadata and controls
58 lines (49 loc) · 1.29 KB
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
<?php
declare(strict_types=1);
/**
* 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): int|float
{
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((string)$octalNumber));
foreach ($octalDigits as $index => $digit) {
$decimalNumber += $digit * 8 ** $index;
}
return $decimalNumber;
}
/**
* This function converts the
* submitted Decimal Number to
* Octal Number.
*
* @param string $decimalNumber
* @throws \Exception
*/
function decimalToOctal($decimalNumber): string
{
if (!is_numeric($decimalNumber)) {
throw new \Exception('Please pass a valid Decimal Number for Converting it to an Octal Number.');
}
$octalNumber = '';
$decimalNumber = (int) $decimalNumber;
while ($decimalNumber > 0) {
$octalNumber = ($decimalNumber % 8) . $octalNumber;
$decimalNumber = intdiv($decimalNumber, 8);
}
return $octalNumber;
}