在Python操作数据内容时,多数情况下可能遇到下面3种类型的数据处理:
hexstring 如:'1C532145697A8B6F'
str 如:'\x1C\x53\x21\x45\x69\x7A\x8B\x6F'
list 如:[0x1C, 0x53, 0x21, 0x45, 0x69, 0x7A, 0x8B, 0x6F]
各种第三方模块(如pyDes),或者自己写的接口中,可能存在由于类型不统一需要在这3种数据中来回切换的情况。
需要用到的核心的方法如下:
list() 将对象转换为list
str() 将对象转换为str
bytearray() 将对象转换为bytearray
bytearray.fromhex() 将对象从hexstring转换为bytearray
binascii.b2a_hex() 将对象从str转换为hexstring
1. 整形列表转str
如:[0x53, 0x21, 0x6A] -> '\x53\x21\x6a'
方法:list -> bytearray -> str
[python]view plaincopy
- x = [0x53, 0x21, 0x6A]
- y = str(bytearray(x))
2. str转整形列表
如:'\x53\x21\6a' -> [0x53, 0x21, 0x6A]
方法:逐个字符转成十进制
[python]view plaincopy
- x = '\x53\x21\x6a'
- y = [ord(c) for c in x]
3. 整形列表转换为hex string
如: [0x53, 0x21, 0x6A] -> '53216A'
方法:list -> bytearray -> str -> hexstring
[python]view plaincopy
- import binascii
- x = [0x53, 0x21, 0x6A]
- y = str(bytearray(x))
- z = binascii.b2a_hex(y)
4. hex string转换为整形列表
如: '53216A' -> [0x53, 0x21, 0x6A]
方法:hexstring -> bytearray -> list
[python]view plaincopy
- x = '53216A'
- y = bytearray.fromhex(x)
- z = list(y)
5. hex string转换为str
如: '53216A' -> '\x53\x21\x6A'
方法:hexstring -> bytearray -> str
[python]view plaincopy
- x = '53216A'
- y = bytearray.fromhex(x)
- z = str(y)
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 = "\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)