2012-03-14 322 views
2

我试图将一串数字转换为'packed hex'格式。Python:将字符串转换为压缩十六进制('01020304' - >' x01 x02 x03 x04')

例如: '01020304' - > '\ X01 \ X02 \ X03 \ X04'

我有工作,但我希望有更好的(更快,更清洁)更Python的方式来做到这一点?

def split_len(seq, length): 
    return [seq[i:i+length] for i in range(0, len(seq), length)] 

def ascii_to_packed_hex(string_data): 
    r""" 
    >>> ascii_to_packed_hex('01') 
    '\x01' 

    >>> ascii_to_packed_hex('0102030405') 
    '\x01\x02\x03\x04\x05' 

    >>> ascii_to_packed_hex('fafbfcfd') 
    '\xfa\xfb\xfc\xfd' 

    >>> ascii_to_packed_hex('31323334') 
    '1234' 
    """    
    hex_data='' 
    string_data = string_data.encode('iso-8859-1') 
    string_parts = split_len(string_data, 2) 

    if len(string_parts)>=1: 
     for each_part in string_parts: 
      encoded_part = each_part[:2] 
      ascii_part = each_part[2:] 
      encoded_part_as_hex = string.atoi(encoded_part,base=16) 
      encoded_part_as_hex = chr(encoded_part_as_hex) 
      hex_data = hex_data + encoded_part_as_hex + ascii_part 
     return hex_data 
    else: 
     return string_data 

    import doctest 
    doctest.testmod() 

回答

4

使用binascii,这是在标准库:

import binascii, doctest 

def ascii_to_packed_hex(string_data): 
    r""" 
    >>> binascii.a2b_hex('01') 
    '\x01' 
    >>> binascii.a2b_hex('0102030405') 
    '\x01\x02\x03\x04\x05' 
    >>> binascii.a2b_hex('fafbfcfd') 
    '\xfa\xfb\xfc\xfd' 
    >>> binascii.a2b_hex('31323334') 
    '1234' 
    """ 
    doctest.testmod() 
2

如果您不能使用binasciistr.decode('hex'),因为这是功课什么的,您可以:

def ascii_to_packed_hex(string_data): 
    # convert each pair of hex digits in the string into an integer 
    # then convert those to characters and join them into a string 
    return ''.join(chr(int(digits, 16)) for digits in 
       (string_data[x:x+2] for x in range(0, len(string_data), 2))) 
3

在Python2中,您可以使用str.decode()

>>> '01'.decode('hex') 
'\x01' 
>>> '0102030405'.decode('hex') 
'\x01\x02\x03\x04\x05' 
>>> 'fafbfcfd'.decode('hex') 
'\xfa\xfb\xfc\xfd' 
>>> '31323334'.decode('hex') 
'1234' 

在Python3,您可以使用bytes.fromhex()

>>> bytes.fromhex('01') 
b'\x01' 
>>> bytes.fromhex('0102030405') 
b'\x01\x02\x03\x04\x05' 
>>> bytes.fromhex('fafbfcfd') 
b'\xfa\xfb\xfc\xfd' 
>>> bytes.fromhex('31323334') 
b'1234' 

如果你想转换为str做到这一点无论与编码你通常的方式是使用

>>> bytes.fromhex('31323334').decode('utf-8') 
'1234' 
+0

Upvote不需要任何进口。 – kindall 2012-03-14 23:05:32

1

你的意思是这样吗?

def ascii_to_packed_hex(s): 
    return "".join(chr(int(s[n:n+2], 16)) for n in range(0,len(s), 2)) 
相关问题