| 1 |
"""
|
| 2 |
HexByteConversion
|
| 3 |
|
| 4 |
Convert a byte string to it's hex representation for output or visa versa.
|
| 5 |
|
| 6 |
ByteToHex converts byte string "\xFF\xFE\x00\x01" to the string "FF FE 00 01"
|
| 7 |
HexToByte converts string "FF FE 00 01" to the byte string "\xFF\xFE\x00\x01"
|
| 8 |
"""
|
| 9 |
|
| 10 |
#-------------------------------------------------------------------------------
|
| 11 |
|
| 12 |
def ByteToHex( byteStr ):
|
| 13 |
"""
|
| 14 |
Convert a byte string to it's hex string representation e.g. for output.
|
| 15 |
"""
|
| 16 |
|
| 17 |
# Uses list comprehension which is a fractionally faster implementation than
|
| 18 |
# the alternative, more readable, implementation below
|
| 19 |
#
|
| 20 |
# hex = []
|
| 21 |
# for aChar in byteStr:
|
| 22 |
# hex.append( "%02X " % ord( aChar ) )
|
| 23 |
#
|
| 24 |
# return ''.join( hex ).strip()
|
| 25 |
|
| 26 |
return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()
|
| 27 |
|
| 28 |
#-------------------------------------------------------------------------------
|
| 29 |
|
| 30 |
def HexToByte( hexStr ):
|
| 31 |
"""
|
| 32 |
Convert a string hex byte values into a byte string. The Hex Byte values may
|
| 33 |
or may not be space separated.
|
| 34 |
"""
|
| 35 |
# The list comprehension implementation is fractionally slower in this case
|
| 36 |
#
|
| 37 |
# hexStr = ''.join( hexStr.split(" ") )
|
| 38 |
# return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \
|
| 39 |
# for i in range(0, len( hexStr ), 2) ] )
|
| 40 |
|
| 41 |
bytes = []
|
| 42 |
|
| 43 |
hexStr = ''.join( hexStr.split(" ") )
|
| 44 |
|
| 45 |
for i in range(0, len(hexStr), 2):
|
| 46 |
bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )
|
| 47 |
|
| 48 |
return ''.join( bytes )
|
| 49 |
|
| 50 |
#-------------------------------------------------------------------------------
|
| 51 |
|
| 52 |
# test data - different formats but equivalent data
|
| 53 |
__hexStr1 = "FFFFFF5F8121070C0000FFFFFFFF5F8129010B"
|
| 54 |
__hexStr2 = "FF FF FF 5F 81 21 07 0C 00 00 FF FF FF FF 5F 81 29 01 0B"
|
| 55 |
__byteStr = "\xFF\xFF\xFF\x5F\x81\x21\x07\x0C\x00\x00\xFF\xFF\xFF\xFF\x5F\x81\x29\x01\x0B"
|
| 56 |
|
| 57 |
|
| 58 |
if __name__ == "__main__":
|
| 59 |
print "\nHex To Byte and Byte To Hex Conversion"
|
| 60 |
|
| 61 |
print "Test 1 - ByteToHex - Passed: ", ByteToHex( __byteStr ) == __hexStr2
|
| 62 |
print "Test 2 - HexToByte - Passed: ", HexToByte( __hexStr1 ) == __byteStr
|
| 63 |
print "Test 3 - HexToByte - Passed: ", HexToByte( __hexStr2 ) == __byteStr
|
| 64 |
|
| 65 |
# turn a non-space separated hex string into a space separated hex string!
|
| 66 |
print "Test 4 - Combined - Passed: ", \
|
| 67 |
ByteToHex( HexToByte( __hexStr1 ) ) == __hexStr2
|