|
2 | 2 |
|
3 | 3 |
|
4 | 4 | def decimal_to_binary(num):
|
5 |
| - """Convert a Decimal Number to a Binary Number.""" |
| 5 | + |
| 6 | + """ |
| 7 | + Convert a Integer Decimal Number to a Binary Number as str. |
| 8 | + >>> decimal_to_binary(0) |
| 9 | + '0b0' |
| 10 | + >>> decimal_to_binary(2) |
| 11 | + '0b10' |
| 12 | + >>> decimal_to_binary(7) |
| 13 | + '0b111' |
| 14 | + >>> decimal_to_binary(35) |
| 15 | + '0b100011' |
| 16 | + >>> # negatives work too |
| 17 | + >>> decimal_to_binary(-2) |
| 18 | + '-0b10' |
| 19 | + >>> # other floats will error |
| 20 | + >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS |
| 21 | + Traceback (most recent call last): |
| 22 | + ... |
| 23 | + TypeError: 'float' object cannot be interpreted as an integer |
| 24 | + >>> # strings will error as well |
| 25 | + >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS |
| 26 | + Traceback (most recent call last): |
| 27 | + ... |
| 28 | + TypeError: 'str' object cannot be interpreted as an integer |
| 29 | + """ |
| 30 | + |
| 31 | + if type(num) == float: |
| 32 | + raise TypeError("'float' object cannot be interpreted as an integer") |
| 33 | + if type(num) == str: |
| 34 | + raise TypeError("'str' object cannot be interpreted as an integer") |
| 35 | + |
| 36 | + if num == 0: |
| 37 | + return "0b0" |
| 38 | + |
| 39 | + negative = False |
| 40 | + |
| 41 | + if num < 0: |
| 42 | + negative = True |
| 43 | + num = -num |
| 44 | + |
6 | 45 | binary = []
|
7 | 46 | while num > 0:
|
8 | 47 | binary.insert(0, num % 2)
|
9 | 48 | num >>= 1
|
10 |
| - return "".join(str(e) for e in binary) |
11 | 49 |
|
| 50 | + if negative: |
| 51 | + return "-0b" + "".join(str(e) for e in binary) |
12 | 52 |
|
13 |
| -def main(): |
14 |
| - """Print binary equivelents of decimal numbers.""" |
15 |
| - print("\n2 in binary is:") |
16 |
| - print(decimal_to_binary(2)) # = 10 |
17 |
| - print("\n7 in binary is:") |
18 |
| - print(decimal_to_binary(7)) # = 111 |
19 |
| - print("\n35 in binary is:") |
20 |
| - print(decimal_to_binary(35)) # = 100011 |
21 |
| - print("\n") |
| 53 | + return "0b" + "".join(str(e) for e in binary) |
22 | 54 |
|
23 | 55 |
|
24 |
| -if __name__ == '__main__': |
25 |
| - main() |
| 56 | +if __name__ == "__main__": |
| 57 | + import doctest |
| 58 | + doctest.testmod() |
0 commit comments