1 Python3中bytes和HexStr之间的转换
- ByteToHex的转换
def ByteToHex( bins ): """ Convert a byte string to it's hex string representation e.g. for output. """ return ''.join( [ "%02X" % x for x in bins ] ).strip()
- HexToByte的转换
def HexToByte( hexStr ): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ return bytes.fromhex(hexStr)
- 测试
__hexStr1 = "FFFFFF5F8121070C0000FFFFFFFF5F8129010B" __hexStr2 = "FF FF FF 5F 81 21 07 0C 00 00 FF FF FF FF 5F 81 29 01 0B" __byteStr = "xFFxFFxFFx5Fx81x21x07x0Cx00x00xFFxFFxFFxFFx5Fx81x29x01x0B" if __name__ == "__main__": print( " Hex To Byte and Byte To Hex Conversion") print( "Test 1 - ByteToHex - Passed: ", ByteToHex( __byteStr ) == __hexStr2) print( "Test 2 - HexToByte - Passed: ", HexToByte( __hexStr1 ) == __byteStr) print( "Test 3 - HexToByte - Passed: ", HexToByte( __hexStr2 ) == __byteStr) # turn a non-space separated hex string into a space separated hex string! print( "Test 4 - Combined - Passed: ", ByteToHex( HexToByte( __hexStr1 ) ) == __hexStr2)