Skip to content

Hacktoberfest: Added Octal Number to Hexadecimal Number Conversion Algorithm #10533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 17, 2023
73 changes: 73 additions & 0 deletions conversions/octal_to_hexadecimal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
def octal_to_hex(octal: str) -> str:
"""
Convert an Octal number to Hexadecimal number.

>>> octal_to_hex("100")
'0X40'
>>> octal_to_hex("235")
'0X9D'
>>> octal_to_hex(17)
Traceback (most recent call last):
...
TypeError: Expected a string as input
>>> octal_to_hex("Av")
Traceback (most recent call last):
...
ValueError: Not a Valid Octal Number
>>> octal_to_hex("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function

For more information: https://en.wikipedia.org/wiki/Octal
"""

if not isinstance(octal, str):
raise TypeError("Expected a string as input")
if octal.startswith("0o"):
octal = octal[2:]
if octal == "":
raise ValueError("Empty string was passed to the function")
for char in octal:
if char not in "01234567":
raise ValueError("Not a Valid Octal Number")

decimal = 0
for char in str(octal):
decimal <<= 3
decimal |= int(char)

hex_char = "0123456789ABCDEF"

revhex = ""
while decimal:
revhex += hex_char[decimal & 15]
decimal >>= 4

hexadecimal = "0X" + revhex[::-1]
return hexadecimal


if __name__ == "__main__":
import doctest

doctest.testmod()

nums = ["030", "100", "247", "235", "007"]

## Main Tests

for num in nums:
hexadecimal = octal_to_hex(num)
expected = hex(int(num, 8)).upper()

assert hexadecimal == expected

print(
"Hex of '0o"
+ num
+ "' is : "
+ hexadecimal
+ " - and Expected was : "
+ expected
)