Skip to content

Commit 1b3fec3

Browse files
binary_to_decimal converter (TheAlgorithms#2400)
* Create binary_to_decimal binary to decimal converter * Update conversions/binary_to_decimal Co-authored-by: Christian Clauss <[email protected]> * Update binary_to_decimal * Update conversions/binary_to_decimal Co-authored-by: Christian Clauss <[email protected]> * Update binary_to_decimal Co-authored-by: Christian Clauss <[email protected]>
1 parent 696cd47 commit 1b3fec3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

conversions/binary_to_decimal

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def 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+
ValueError: Non-binary value was passed to the function
15+
>>> bin_to_decimal("")
16+
ValueError: Empty string value was passed to the function
17+
>>> bin_to_decimal("39")
18+
ValueError: Non-binary value was passed to the function
19+
"""
20+
bin_string = str(bin_string).strip()
21+
if not bin_string:
22+
raise ValueError("Empty string was passed to the function")
23+
is_negative = bin_string[0] == "-"
24+
if is_negative:
25+
bin_string = bin_string[1:]
26+
if not all(char in "01" for char in bin_string):
27+
raise ValueError("Non-binary value was passed to the function")
28+
decimal_number = 0
29+
for char in bin_string:
30+
decimal_number = 2 * decimal_number + int(char)
31+
if is_negative:
32+
decimal_number = -decimal_number
33+
return decimal_number
34+
35+
36+
if __name__ == "__main__":
37+
from doctest import testmod
38+
39+
testmod()

0 commit comments

Comments
 (0)