Last active
June 20, 2019 15:32
-
-
Save i96751414/b1ed2aef2cb9f602d03c305e22cb6e13 to your computer and use it in GitHub Desktop.
Automatically convert integers to hex strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bytes_size(value): | |
if value == 0: | |
return 1 | |
size = (value.bit_length() + 7) // 8 | |
if value < 0 and not value & (1 << (size * 8 - 1)): | |
size += 1 | |
return size | |
def integer_to_hex(value, decimals=0): | |
if decimals % 2 != 0: | |
decimals += 1 | |
nibbles = bytes_size(value) * 2 | |
hex_string = hex(value & (2 ** (nibbles * 4) - 1))[2:].upper() | |
return ((nibbles if nibbles > decimals else decimals) - len(hex_string)) * ("F" if value < 0 else "0") + hex_string | |
def integer_to_str(value, decimals=0): | |
if value < 0: | |
decimals += 1 | |
return str(value).zfill(decimals) | |
if __name__ == '__main__': | |
for i in range(256): | |
print(-i) | |
print(integer_to_hex(-i, 4)) | |
print(integer_to_str(-i, 3)) | |
print("----") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment