Skip to content

Instantly share code, notes, and snippets.

@wamsachel
Created October 21, 2016 20:45
Show Gist options
  • Select an option

  • Save wamsachel/22ea9c5914d5a55b97c1b6f175d99b97 to your computer and use it in GitHub Desktop.

Select an option

Save wamsachel/22ea9c5914d5a55b97c1b6f175d99b97 to your computer and use it in GitHub Desktop.
Converts a decimal value into a hex byte string
def gen_bytestr(dec_val, byte_str_len=4):
""" takes dec_val, converts to hex and returns byte_str that is byte_str_len long
e.g. gen_bytestr(255, 4) -> '\x00\x00\x00\xff'
"""
# first check if dec_val can even be represented by a byte string of byte_str_len length
byte_count = (int.bit_length(dec_val) / 4)
if byte_count > byte_str_len:
raise Exception('[!] {val} too large for {max} byte length. (requires {req} bytes)'.format(
val=dec_val, max=byte_str_len, req=byte_count))
hex_val = hex(dec_val)
hex_val = hex_val[2:] # hex() prepends '0x' to val, strip it
hex_val = hex_val.zfill(byte_str_len * 2) # fill out with 0's to fit byte_str_len
a_bytearray = bytearray.fromhex(hex_val)
return a_bytearray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment