Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically convert integers to hex strings
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
You can’t perform that action at this time.