decimal to binary Algorithm
In computing and electronic systems, binary-coded decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of bits, normally four or eight. In byte-oriented systems (i.e. most modern computers), the term unpacked BCD normally imply a full byte for each digit (often including a sign), whereas packed BCD typically encodes two decimal digits within a individual byte by take advantage of the fact that four bits are enough to represent the range 0 to 9.
"""Convert a Decimal Number to a Binary Number."""
def decimal_to_binary(num: int) -> str:
"""
Convert a Integer Decimal Number to a Binary Number as str.
>>> 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
binary = []
while num > 0:
binary.insert(0, num % 2)
num >>= 1
if negative:
return "-0b" + "".join(str(e) for e in binary)
return "0b" + "".join(str(e) for e in binary)
if __name__ == "__main__":
import doctest
doctest.testmod()