mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 15:01:08 +00:00
binary_to_decimal converter (#2400)
* Create binary_to_decimal binary to decimal converter * Update conversions/binary_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> * Update binary_to_decimal * Update conversions/binary_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> * Update binary_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
696cd47e15
commit
1b3fec3f1f
39
conversions/binary_to_decimal
Normal file
39
conversions/binary_to_decimal
Normal file
|
@ -0,0 +1,39 @@
|
|||
def bin_to_decimal(bin_string: str) -> int:
|
||||
"""
|
||||
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")
|
||||
ValueError: Non-binary value was passed to the function
|
||||
>>> bin_to_decimal("")
|
||||
ValueError: Empty string value was passed to the function
|
||||
>>> bin_to_decimal("39")
|
||||
ValueError: Non-binary value was passed to the function
|
||||
"""
|
||||
bin_string = str(bin_string).strip()
|
||||
if not bin_string:
|
||||
raise ValueError("Empty string was passed to the function")
|
||||
is_negative = bin_string[0] == "-"
|
||||
if is_negative:
|
||||
bin_string = bin_string[1:]
|
||||
if not all(char in "01" for char in bin_string):
|
||||
raise ValueError("Non-binary value was passed to the function")
|
||||
decimal_number = 0
|
||||
for char in bin_string:
|
||||
decimal_number = 2 * decimal_number + int(char)
|
||||
if is_negative:
|
||||
decimal_number = -decimal_number
|
||||
return decimal_number
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from doctest import testmod
|
||||
|
||||
testmod()
|
Loading…
Reference in New Issue
Block a user