BYTE TO HEX AND HEX TO BYTE STRING CONVERSION

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BYTE TO HEX AND HEX TO BYTE STRING CONVERSION相关的知识,希望对你有一定的参考价值。

I write a lot of ad-hoc protocol analysers using Python. Generally, I‘m dealing with a byte stream that I want to output as a string of hex. Sometimes, I want to convert it back again. Eventually, I got round to putting the functions in a module so I wouldn‘t keep cut and pasting them :)

"""
HexByteConversion

Convert a byte string to it‘s hex representation for output or visa versa.

ByteToHex converts byte string "\xFF\xFE\x00\x01" to the string "FF FE 00 01"
HexToByte converts string "FF FE 00 01" to the byte string "\xFF\xFE\x00\x01"
"""

#-------------------------------------------------------------------------------

def ByteToHex( byteStr ):
    """
    Convert a byte string to it‘s hex string representation e.g. for output.
    """

    # Uses list comprehension which is a fractionally faster implementation than
    # the alternative, more readable, implementation below
    #   
    #    hex = []
    #    for aChar in byteStr:
    #        hex.append( "%02X " % ord( aChar ) )
    #
    #    return ‘‘.join( hex ).strip()        

    return ‘‘.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()

#-------------------------------------------------------------------------------

def HexToByte( hexStr ):
    """
    Convert a string hex byte values into a byte string. The Hex Byte values may
    or may not be space separated.
    """
    # The list comprehension implementation is fractionally slower in this case    
    #
    #    hexStr = ‘‘.join( hexStr.split(" ") )
    #    return ‘‘.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) )     #                                   for i in range(0, len( hexStr ), 2) ] )

    bytes = []

    hexStr = ‘‘.join( hexStr.split(" ") )

    for i in range(0, len(hexStr), 2):
        bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )

    return ‘‘.join( bytes )

#-------------------------------------------------------------------------------

# test data - different formats but equivalent data
__hexStr1  = "FFFFFF5F8121070C0000FFFFFFFF5F8129010B"
__hexStr2  = "FF FF FF 5F 81 21 07 0C 00 00 FF FF FF FF 5F 81 29 01 0B"
__byteStr = "\xFF\xFF\xFF\x5F\x81\x21\x07\x0C\x00\x00\xFF\xFF\xFF\xFF\x5F\x81\x29\x01\x0B"

if __name__ == "__main__":
    print "\nHex 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

I don‘t want to start a ‘one line bubble sort‘ kind of competition here but, if anyone can come up with a line comprehension implementation for the HexToByte function that is faster than the alternative, that would be interesting.

以上是关于BYTE TO HEX AND HEX TO BYTE STRING CONVERSION的主要内容,如果未能解决你的问题,请参考以下文章

STRING TO HEX 如何在向量中添加 ob 字节?

PHP Str To Hex / Hex To Str

仿真时候Proteus显示Unable to open HEX file 错误解决方法

Str到Hex/Hex到Str

HEX格式数据转换成十六进制字符串

linux内核算法---hex_to_bin分享