take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hex
(decimal: float)
| 22 | |
| 23 | |
| 24 | def decimal_to_hexadecimal(decimal: float) -> str: |
| 25 | """ |
| 26 | take integer decimal value, return hexadecimal representation as str beginning |
| 27 | with 0x |
| 28 | >>> decimal_to_hexadecimal(5) |
| 29 | '0x5' |
| 30 | >>> decimal_to_hexadecimal(15) |
| 31 | '0xf' |
| 32 | >>> decimal_to_hexadecimal(37) |
| 33 | '0x25' |
| 34 | >>> decimal_to_hexadecimal(255) |
| 35 | '0xff' |
| 36 | >>> decimal_to_hexadecimal(4096) |
| 37 | '0x1000' |
| 38 | >>> decimal_to_hexadecimal(999098) |
| 39 | '0xf3eba' |
| 40 | >>> # negatives work too |
| 41 | >>> decimal_to_hexadecimal(-256) |
| 42 | '-0x100' |
| 43 | >>> # floats are acceptable if equivalent to an int |
| 44 | >>> decimal_to_hexadecimal(17.0) |
| 45 | '0x11' |
| 46 | >>> # other floats will error |
| 47 | >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS |
| 48 | Traceback (most recent call last): |
| 49 | ... |
| 50 | AssertionError |
| 51 | >>> # strings will error as well |
| 52 | >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS |
| 53 | Traceback (most recent call last): |
| 54 | ... |
| 55 | AssertionError |
| 56 | >>> # results are the same when compared to Python's default hex function |
| 57 | >>> decimal_to_hexadecimal(-256) == hex(-256) |
| 58 | True |
| 59 | """ |
| 60 | assert isinstance(decimal, (int, float)) |
| 61 | assert decimal == int(decimal) |
| 62 | decimal = int(decimal) |
| 63 | hexadecimal = "" |
| 64 | negative = False |
| 65 | if decimal < 0: |
| 66 | negative = True |
| 67 | decimal *= -1 |
| 68 | while decimal > 0: |
| 69 | decimal, remainder = divmod(decimal, 16) |
| 70 | hexadecimal = values[remainder] + hexadecimal |
| 71 | hexadecimal = "0x" + hexadecimal |
| 72 | if negative: |
| 73 | hexadecimal = "-" + hexadecimal |
| 74 | return hexadecimal |
| 75 | |
| 76 | |
| 77 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected