Created
August 7, 2013 05:27
-
-
Save lsparrish/6171447 to your computer and use it in GitHub Desktop.
Simple byte array to hex string converter
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
'' | |
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