File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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()
You can’t perform that action at this time.
0 commit comments