MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / bin_to_decimal

Function bin_to_decimal

conversions/binary_to_decimal.py:1–37  ·  view source on GitHub ↗

Convert a binary value to its decimal equivalent >>> bin_to_decimal("101") 5 >>> bin_to_decimal(" 1010 ") 10 >>> bin_to_decimal("-11101") -29 >>> bin_to_decimal("0") 0 >>> bin_to_decimal("a") Traceback (most recent call last): ... ValueErro

(bin_string: str)

Source from the content-addressed store, hash-verified

1def bin_to_decimal(bin_string: str) -> int:
2 """
3 Convert a binary value to its decimal equivalent
4
5 >>> bin_to_decimal("101")
6 5
7 >>> bin_to_decimal(" 1010 ")
8 10
9 >>> bin_to_decimal("-11101")
10 -29
11 >>> bin_to_decimal("0")
12 0
13 >>> bin_to_decimal("a")
14 Traceback (most recent call last):
15 ...
16 ValueError: Non-binary value was passed to the function
17 >>> bin_to_decimal("")
18 Traceback (most recent call last):
19 ...
20 ValueError: Empty string was passed to the function
21 >>> bin_to_decimal("39")
22 Traceback (most recent call last):
23 ...
24 ValueError: Non-binary value was passed to the function
25 """
26 bin_string = str(bin_string).strip()
27 if not bin_string:
28 raise ValueError("Empty string was passed to the function")
29 is_negative = bin_string[0] == "-"
30 if is_negative:
31 bin_string = bin_string[1:]
32 if not all(char in "01" for char in bin_string):
33 raise ValueError("Non-binary value was passed to the function")
34 decimal_number = 0
35 for char in bin_string:
36 decimal_number = 2 * decimal_number + int(char)
37 return -decimal_number if is_negative else decimal_number
38
39
40if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected