-
-
Notifications
You must be signed in to change notification settings - Fork 586
Expand file tree
/
Copy pathBinaryToDecimal.php
More file actions
34 lines (29 loc) · 739 Bytes
/
Copy pathBinaryToDecimal.php
File metadata and controls
34 lines (29 loc) · 739 Bytes
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
<?php
declare(strict_types=1);
/**
* This function converts the
* submitted Binary Number to
* Decimal Number.
*
* Working of Algorithm
* (10) base 2
* (1 * (2 ^ 1) + 0 * (2 ^ 0)) base 10
* (2 + 0) base 10
* 2 base 10
*
* @param string $binaryNumber
* @return int
* @throws \Exception
*/
function binaryToDecimal($binaryNumber): int|float
{
if (!is_numeric($binaryNumber)) {
throw new \Exception('Please pass a valid Binary Number for Converting it to a Decimal Number.');
}
$decimalNumber = 0;
$binaryDigits = array_reverse(str_split((string)$binaryNumber));
foreach ($binaryDigits as $index => $digit) {
$decimalNumber += $digit * 2 ** $index;
}
return $decimalNumber;
}