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)
| 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 | 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 | |
| 40 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected