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 strin
(octal: str)
| 1 | def octal_to_hex(octal: str) -> str: |
| 2 | """ |
| 3 | Convert an Octal number to Hexadecimal number. |
| 4 | For more information: https://en.wikipedia.org/wiki/Octal |
| 5 | |
| 6 | >>> octal_to_hex("100") |
| 7 | '0x40' |
| 8 | >>> octal_to_hex("235") |
| 9 | '0x9D' |
| 10 | >>> octal_to_hex(17) |
| 11 | Traceback (most recent call last): |
| 12 | ... |
| 13 | TypeError: Expected a string as input |
| 14 | >>> octal_to_hex("Av") |
| 15 | Traceback (most recent call last): |
| 16 | ... |
| 17 | ValueError: Not a Valid Octal Number |
| 18 | >>> octal_to_hex("") |
| 19 | Traceback (most recent call last): |
| 20 | ... |
| 21 | ValueError: Empty string was passed to the function |
| 22 | """ |
| 23 | |
| 24 | if not isinstance(octal, str): |
| 25 | raise TypeError("Expected a string as input") |
| 26 | if octal.startswith("0o"): |
| 27 | octal = octal[2:] |
| 28 | if octal == "": |
| 29 | raise ValueError("Empty string was passed to the function") |
| 30 | if any(char not in "01234567" for char in octal): |
| 31 | raise ValueError("Not a Valid Octal Number") |
| 32 | |
| 33 | decimal = 0 |
| 34 | for char in octal: |
| 35 | decimal <<= 3 |
| 36 | decimal |= int(char) |
| 37 | |
| 38 | hex_char = "0123456789ABCDEF" |
| 39 | |
| 40 | revhex = "" |
| 41 | while decimal: |
| 42 | revhex += hex_char[decimal & 15] |
| 43 | decimal >>= 4 |
| 44 | |
| 45 | return "0x" + revhex[::-1] |
| 46 | |
| 47 | |
| 48 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected