Skip to content

Instantly share code, notes, and snippets.

@lsparrish
Created August 7, 2013 05:27
Show Gist options
  • Save lsparrish/6171447 to your computer and use it in GitHub Desktop.
Save lsparrish/6171447 to your computer and use it in GitHub Desktop.
Simple byte array to hex string converter
''
Python BIFs hex() and int() are fairly useful, but byte arrays seem to trip them up.
'''
'''random key (byte array)'''
from os import urandom
key=urandom(32)
'''hex string functions'''
def toHex(x):
'''byte array->hex string'''
numerals="0123456789abcdef"
result=""
for y in x:
result=result+(numerals[int(int(y)/16)]+numerals[int(int(y)%16)])
return '0x'+result
def fromHex(x):
'''hex string->byte array'''
numerals="0123456789abcdef"
result=[]
x=x[2:]
for i in range(int(len(x)/2)):
a=numerals.find(x[i*2])
b=numerals.find(x[i*2+1])
result.append(a*16+b)
return bytes(result)
if fromHex(toHex(key))==key:
print("fromHex(toHex(key)) == key")
else:
print("fromHex(toHex(key)) != key")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment