Skip to content

Instantly share code, notes, and snippets.

@edobez
Created March 13, 2018 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edobez/710aec3304489cf0f3f8bcd89800f2da to your computer and use it in GitHub Desktop.
Save edobez/710aec3304489cf0f3f8bcd89800f2da to your computer and use it in GitHub Desktop.
Python: bytes to hex string
def byte2hexstring(b, spacing=" ", upper_case=True):
"""
Converts bytes into hex string.
Args:
b (bytes): Bytes to be converted
spacing (string): Spacing between each couple of hex charachters. Defaults to single space
upper_case: If True, uses upper-case letters for the digits above 9
Returns:
String with hex representation of input bytes
Example:
>>> byte2hexstring(b"\xde\xad\xbe\xef")
"DE AD BE EF"
"""
if upper_case:
hex_format = "%2.2X"
else:
hex_format = "%2.2x"
return spacing.join(list(map(hex_format.__mod__, b)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment