从以十六进制编码的ASCII字符串转换为纯ASCII?

时间:2012-03-09 21:47:30

标签: python hex ascii

如何在Python中将十六进制转换为纯ASCII?

请注意,例如,我想将“0x7061756c”转换为“paul”。

8 个答案:

答案 0 :(得分:205)

一个稍微简单的解决方案:

>>> "7061756c".decode("hex")
'paul'

答案 1 :(得分:73)

无需导入任何库:

>>> bytearray.fromhex("7061756c").decode()
'paul'

答案 2 :(得分:43)

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

我只是玩得开心,但重要的部分是:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

现在看看binascii ......

>>> print binascii.unhexlify('7061756c')
paul
很酷(而且我不知道为什么其他人想要让他们在他们帮助之前跳过篮球。)

答案 3 :(得分:5)

使用十六进制整数而非十六进制字符串时,这是我的解决方案:

def convert_hex_to_ascii(h):
    chars_in_reverse = []
    while h != 0x0:
        chars_in_reverse.append(chr(h & 0xFF))
        h = h >> 8

    chars_in_reverse.reverse()
    return ''.join(chars_in_reverse)

print convert_hex_to_ascii(0x7061756c)

答案 4 :(得分:5)

在Python 2中:

>>> "7061756c".decode("hex")
'paul'

在Python 3中:

>>> bytes.fromhex('7061756c').decode('utf-8')
'paul'

答案 5 :(得分:3)

在Python 3.3.2中测试 有很多方法可以实现这一点,这是最短的方法之一,只使用python提供的东西:

import base64
hex_data ='57696C6C20796F7520636F6E76657274207468697320484558205468696E6720696E746F20415343494920666F72206D653F2E202E202E202E506C656565656173652E2E2E212121'
ascii_string = str(base64.b16decode(hex_data))[2:-1]
print (ascii_string)

当然,如果您不想导入任何内容,您可以随时编写自己的代码。像这样非常基本的东西:

ascii_string = ''
x = 0
y = 2
l = len(hex_data)
while y <= l:
    ascii_string += chr(int(hex_data[x:y], 16))
    x += 2
    y += 2
print (ascii_string)

答案 6 :(得分:2)

或者,你也可以这样做......

Python解释器

print "\x70 \x61 \x75 \x6c"

实施例

user@linux:~# python
Python 2.7.14+ (default, Mar 13 2018, 15:23:44) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "\x70 \x61 \x75 \x6c"
p a u l
>>> exit()
user@linux:~# 

Python One-Liner

python -c 'print "\x70 \x61 \x75 \x6c"'

实施例

user@linux:~# python -c 'print "\x70 \x61 \x75 \x6c"'
p a u l
user@linux:~# 

答案 7 :(得分:0)

b''.fromhex('7061756c')

使用不带分隔符的

相关问题