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.

原文地址:http://blog.51cto.com/zhaoanan/2062980

时间: 2024-10-19 09:46:01

BYTE TO HEX AND HEX TO BYTE STRING CONVERSION的相关文章

byte数组转float实现与byte转换其它类型时进行&运算原理

下面是将byte数组转换为float的实现 public static float getFloat(byte[] b) { int accum = 0; accum = accum|(b[0] & 0xff) << 0; accum = accum|(b[1] & 0xff) << 8; accum = accum|(b[2] & 0xff) << 16; accum = accum|(b[3] & 0xff) << 24;

Byte,TBytes,array of Byte, array[0..9] of byte的区别

Byte前面已经说是存放bit的单元,是电脑内存的基本单位,byte表示0-255中的256个数字 下面为Byte的用法: var B: Byte; // 表示0-255的数字 begin B := 1; Log(B.ToString()); //1 B := 255; Log(B.ToString()); //255 end; 下面将Char转换成Byte: var C: Char; // char 表示字符任意字符 begin C := '1'; Log(C); // 1 Log(SizeO

ATL and MFC String Conversion Macros

ATL 7.0介绍了一些新的转换类和宏,为现有的宏提供了重要的改进.新的字符串转换类和名称宏的形式是:C 源类型 2[C] 目标类型[EX]其中:•源类型和目标类型描述如下表.• [C]是目标类型必须是只读的.•[EX]是缓冲器的初始大小必须被指定为一个模板参数. 源类型/目标类型  描述 A  ANSI字符串 W  Unicode字符串 T  通用字符串(如果定义了_UNICODE)则等同于W,否则等同于A OLE  OLE字符串(等同于W) 例如,从一个Unicode字符串转换为普通字符串不

Notice:Array to string conversion的问题

如果后台或者前端输出这样的提示: Notice: Array to string conversion 原因是:用 echo  来输出数组,当然会报错,数组应该用print , print_r , 或者 var_dump来打印: 如果你在前端的嵌套PHP代码,想将一个数组赋值给一个变量,像这样的: 1 <script> 2 var text = <?php echo $text;?>; //$text是一个数组的话,就会报错 3 </script> 4 5 解决方法:

byte[]转int,int转byte[]

b = new byte[] {0xfe,0x5a,0x11,0xfa}; u = (uint)(b[0] | b[1] << 8 |    b[2] << 16 | b[3] << 24); b[0] = (byte)(u); b[1] = (byte)(u >> 8); b[2] = (byte)(u >> 16); b[3] = (byte)(u >> 24);

byte to object and object to byte

public byte[] Serialize() { var bf = newBinaryFormatter(); using (var ms = newMemoryStream()) { using (var ds = newDeflateStream(ms, CompressionMode.Compress, true)) { bf.Serialize(ds, this); } return ms.ToArray(); } } publicstaticMiniPCMessage Deser

php,二维数组的输出出现了问题,提示:Notice: Array to string conversion

<?php $arr=array(array("111","222","333"),array("444","555","666")); print_r("{$arr[0][1]}"); ?> 这样就可以了,多维数组.以及下标不是简单数值的数组,都需要{}起来. 将数据传递到javascript中时同样适用

byte ---&gt; hex String

public static String byte2HexString(byte[] b){ String ret = ""; for(int i=0;i<b.lenght;i++){ String hex = Integer.toHexString(b[i]&0XFF); if(hex.length()==1){ hex = '0'+hex; } ret+=hex.toUpperCase(); } return ret; } 1  1个字节8位 1个BYTE与上2个he

C#中的Byte,String,Int,Hex之间的转换函数。

/// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary> /// <param name="s"> The string containing the hex digits (with or without spaces). </param> /// <returns> Returns an array of