forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
octal_to_hexadecimal.py
65 lines (51 loc) · 1.59 KB
/
octal_to_hexadecimal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def octal_to_hex(octal: str) -> str:
"""
Convert an Octal number to Hexadecimal number.
For more information: https://en.wikipedia.org/wiki/Octal
>>> 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
"""
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")
if any(char not in "01234567" for char in octal):
raise ValueError("Not a Valid Octal Number")
decimal = 0
for char in octal:
decimal <<= 3
decimal |= int(char)
hex_char = "0123456789ABCDEF"
revhex = ""
while decimal:
revhex += hex_char[decimal & 15]
decimal >>= 4
return "0x" + revhex[::-1]
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 = "0x" + hex(int(num, 8))[2:].upper()
assert hexadecimal == expected
print(f"Hex of '0o{num}' is: {hexadecimal}")
print(f"Expected was: {expected}")
print("---")