|
| 1 | +""" |
| 2 | +* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) |
| 3 | +* Description: Convert a Octal number to Binary. |
| 4 | +
|
| 5 | +References for better understanding: |
| 6 | +https://en.wikipedia.org/wiki/Binary_number |
| 7 | +https://en.wikipedia.org/wiki/Octal |
| 8 | +""" |
| 9 | + |
| 10 | + |
| 11 | +def octal_to_binary(octal_number: str) -> str: |
| 12 | + """ |
| 13 | + Convert an Octal number to Binary. |
| 14 | +
|
| 15 | + >>> octal_to_binary("17") |
| 16 | + '001111' |
| 17 | + >>> octal_to_binary("7") |
| 18 | + '111' |
| 19 | + >>> octal_to_binary("Av") |
| 20 | + Traceback (most recent call last): |
| 21 | + ... |
| 22 | + ValueError: Non-octal value was passed to the function |
| 23 | + >>> octal_to_binary("@#") |
| 24 | + Traceback (most recent call last): |
| 25 | + ... |
| 26 | + ValueError: Non-octal value was passed to the function |
| 27 | + >>> octal_to_binary("") |
| 28 | + Traceback (most recent call last): |
| 29 | + ... |
| 30 | + ValueError: Empty string was passed to the function |
| 31 | + """ |
| 32 | + if not octal_number: |
| 33 | + raise ValueError("Empty string was passed to the function") |
| 34 | + |
| 35 | + binary_number = "" |
| 36 | + octal_digits = "01234567" |
| 37 | + for digit in octal_number: |
| 38 | + if digit not in octal_digits: |
| 39 | + raise ValueError("Non-octal value was passed to the function") |
| 40 | + |
| 41 | + binary_digit = "" |
| 42 | + value = int(digit) |
| 43 | + for _ in range(3): |
| 44 | + binary_digit = str(value % 2) + binary_digit |
| 45 | + value //= 2 |
| 46 | + binary_number += binary_digit |
| 47 | + |
| 48 | + return binary_number |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + import doctest |
| 53 | + |
| 54 | + doctest.testmod() |
0 commit comments