简体   繁体   English

Python:将字符串转换为压缩十六进制('01020304' - >'\\ x01 \\ x02 \\ x03 \\ x04')

[英]Python: convert string to packed hex ( '01020304' -> '\x01\x02\x03\x04' )

I'm trying to convert a string of numbers into a 'packed hex' format. 我正在尝试将一串数字转换为'压缩十六进制'格式。

For example: '01020304' -> '\\x01\\x02\\x03\\x04' 例如:'01020304' - >'\\ x01 \\ x02 \\ x03 \\ x04'

I have it working, but I expect there are better (faster, cleaner) more pythonic ways to do this? 我有它工作,但我希望有更好的(更快,更清洁)更pythonic方式来做到这一点?

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()

Use binascii , which is in the standard library: 使用标准库中的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()

In Python2 you can use use str.decode() 在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'

In Python3 you can use bytes.fromhex() 在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'

If you wish to convert to a str do it the usual way with whichever encoding you are using 如果您希望转换为str请使用您使用的任何编码通常的方式

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

If you can't use binascii or str.decode('hex') because this is homework or something, you can: 如果你不能使用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)))

You mean like this? 你的意思是这样的?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字符串字节转换为字节,例如 b'\x00\x01\x02' - Convert string byte to byte like b'\x00\x01\x02' how to store bytes like b'PK\x03\x04\x14\x00\x08\x08\x08\x009bwR\x00\x00\x00\x00\x00\x00\x00 to dataframe or csv in python - how to store bytes like b'PK\x03\x04\x14\x00\x08\x08\x08\x009bwR\x00\x00\x00\x00\x00\x00\x00 to dataframe or csv in python python如何将特殊字符串u'\\ x08'u'\\ x09'u'\\ x03'转换为8 9 3 - python how to convert Special string u'\x08' u'\x09' u'\x03' to 8 9 3 为什么对两个十六进制字符串进行异或运算会产生以下格式的输出:'\\ x02 \\ x07 \\ x01P \\ x00 \\ x07 - Why XORing two hex strings produce an output in the following format: '\x02\x07\x01P\x00\x07 如何使用 Python 将字节数组 b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04' 转换为可读字符串“20600”? - How to covert byte array b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04' to Readable character string “20600” using Python? 将带有\\ x01字符的字符串保存到磁盘 - Saving a string with \x01 characters to disk 从字符串中剥离\\ x00和\\ x02 - Strip \x00 and \x02 from string Windows上的Python Unicode文件名\\ x01 - Python Unicode filename \x01 on Windows 如何将'\\ x01'变为1 - How to get '\x01' to 1 从python读取BerkleyDB文件:\\ x01 \\ x0b \\ x88 \\ x0c \\ x01`? - Reading BerkleyDB files from python: `\x01\x0b\x88\x0c\x01`?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM