Python/conversions/octal_to_binary.py

71 lines
1.9 KiB
Python
Raw Normal View History

2023-08-18 11:45:30 +05:30
"""
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
* Description: Convert a Octal number to Binary.
2023-08-19 01:06:44 +05:30
References for better understanding:
https://en.wikipedia.org/wiki/Binary_number
https://en.wikipedia.org/wiki/Octal
2023-08-18 11:45:30 +05:30
"""
def octal_to_binary(octal_number: str) -> str:
2023-08-18 11:45:30 +05:30
"""
2023-08-19 20:17:49 +05:30
Convert an Octal number to Binary.
ValueError: Non-octal value was passed to the function
>>> octal_to_binary("Av")
2023-08-18 11:45:30 +05:30
Traceback (most recent call last):
...
ValueError: Non-octal value was passed to the function
2023-08-19 20:17:49 +05:30
ValueError: Special Character was passed to the function
>>> octal_to_binary("@#")
2023-08-18 11:45:30 +05:30
Traceback (most recent call last):
...
2023-08-18 12:47:09 +05:30
ValueError: Special Character was passed to the function
2023-08-19 20:17:49 +05:30
ValueError: Empty String was passed to the function
>>> octal_to_binary("")
2023-08-18 12:47:09 +05:30
Traceback (most recent call last):
...
ValueError: Empty String was passed to the function
2023-08-19 20:17:49 +05:30
ValueError: Octal value was passed to the function
>>> octal_to_binary("17")
'001111'
ValueError: Octal value was passed to the function
>>> octal_to_binary("7")
'111'
2023-08-18 11:45:30 +05:30
"""
2023-08-19 20:17:49 +05:30
if not octal_number:
raise ValueError("Empty String was passed to the function")
for digit in octal_number:
if not digit.isdigit():
raise ValueError("Special Character was passed to the function")
if digit < "0" or digit > "7":
2023-08-19 20:17:49 +05:30
raise ValueError("Non-octal value was passed to the function")
2023-08-19 01:06:44 +05:30
binary_number = ""
octal_digits = "01234567"
2023-08-13 14:20:02 +05:30
for digit in octal_number:
if digit not in octal_digits:
2023-08-19 20:17:49 +05:30
raise ValueError("Octal value was passed to the function")
2023-08-13 14:20:02 +05:30
binary_digit = ""
value = int(digit)
for _ in range(3):
binary_digit = str(value % 2) + binary_digit
value //= 2
binary_number += binary_digit
return binary_number
2023-08-11 17:11:58 +05:30
if __name__ == "__main__":
import doctest
doctest.testmod()