2019-07-05 08:36:48 +00:00
|
|
|
"""Convert a Decimal Number to a Binary Number."""
|
|
|
|
|
|
|
|
|
2020-06-02 14:47:10 +00:00
|
|
|
def decimal_to_binary(num: int) -> str:
|
2019-08-03 18:00:10 +00:00
|
|
|
|
|
|
|
"""
|
2020-07-07 11:26:10 +00:00
|
|
|
Convert an Integer Decimal Number to a Binary Number as str.
|
2019-08-03 18:00:10 +00:00
|
|
|
>>> decimal_to_binary(0)
|
|
|
|
'0b0'
|
|
|
|
>>> decimal_to_binary(2)
|
|
|
|
'0b10'
|
|
|
|
>>> decimal_to_binary(7)
|
|
|
|
'0b111'
|
|
|
|
>>> decimal_to_binary(35)
|
|
|
|
'0b100011'
|
|
|
|
>>> # negatives work too
|
|
|
|
>>> decimal_to_binary(-2)
|
|
|
|
'-0b10'
|
|
|
|
>>> # other floats will error
|
|
|
|
>>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
TypeError: 'float' object cannot be interpreted as an integer
|
|
|
|
>>> # strings will error as well
|
|
|
|
>>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
TypeError: 'str' object cannot be interpreted as an integer
|
|
|
|
"""
|
|
|
|
|
|
|
|
if type(num) == float:
|
|
|
|
raise TypeError("'float' object cannot be interpreted as an integer")
|
|
|
|
if type(num) == str:
|
|
|
|
raise TypeError("'str' object cannot be interpreted as an integer")
|
|
|
|
|
|
|
|
if num == 0:
|
|
|
|
return "0b0"
|
|
|
|
|
|
|
|
negative = False
|
|
|
|
|
|
|
|
if num < 0:
|
|
|
|
negative = True
|
|
|
|
num = -num
|
|
|
|
|
2019-07-05 08:36:48 +00:00
|
|
|
binary = []
|
|
|
|
while num > 0:
|
|
|
|
binary.insert(0, num % 2)
|
|
|
|
num >>= 1
|
|
|
|
|
2019-08-03 18:00:10 +00:00
|
|
|
if negative:
|
|
|
|
return "-0b" + "".join(str(e) for e in binary)
|
2019-07-05 08:36:48 +00:00
|
|
|
|
2019-08-03 18:00:10 +00:00
|
|
|
return "0b" + "".join(str(e) for e in binary)
|
2019-07-05 08:36:48 +00:00
|
|
|
|
|
|
|
|
2019-08-03 18:00:10 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-08-03 18:00:10 +00:00
|
|
|
doctest.testmod()
|