简体   繁体   English

Python - 从文件打印十六进制

[英]Python - Printing Hex from a file

I have the following code:我有以下代码:

code1 = ("\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1")
print code1

code2 = open("code.txt", 'rb').read()
print code2

code1 output:代码1 output:

�צ�t$פ_)�½i�»±

code2 output:代码2 output:

"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"

I need code2 (which I read from a file) to have the same output as code1.我需要code2(我从文件中读取)具有与code1相同的output。
How can i solve this?我该如何解决这个问题?

To interpret a sequence of characters such as解释一系列字符,例如

In [125]: list(code2[:8])
Out[125]: ['\\', 'x', 'd', '9', '\\', 'x', 'f', '6']

as Python would a string with escaped characters, such as因为 Python 将是一个带有转义字符的字符串,例如

In [132]: list('\xd9\xf6')
Out[132]: ['\xd9', '\xf6']

use .decode('string_escape') :使用.decode('string_escape')

In [122]: code2.decode('string_escape')
Out[122]: '\xd9\xf6\xd9t$\xf4_)\xc9\xbdi\xd1\xbb\x18\xb1'

In Python3, the string_escape codec has been removed, so the equivalent becomes在 Python3 中, string_escape编解码器已被删除,因此等效变为

import codecs
codecs.escape_decode(code2)[0]

This example:这个例子:

import binascii

code1 = "\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
code2 = "\\xd9\\xf6\\xd9\\x74\\x24\\xf4\\x5f\\x29\\xc9\\xbd\\x69\\xd1\\xbb\\x18\\xb1"

print code1 == binascii.unhexlify(code2.replace('\\x', ''))

prints True .打印True

You can use binascii.unhexlify to convert hexadecimal text representation to binary, but first have to remove \x from the string.您可以使用binascii.unhexlify将十六进制文本表示转换为二进制,但首先必须从字符串中删除\x

EDIT : I've just realised that double quotes are part of your output.编辑:我刚刚意识到双引号是您的 output 的一部分。 Essentially you need to pass just valid hex string, so everything else need to be stripped off.本质上,您只需要传递有效的十六进制字符串,因此需要剥离其他所有内容。 In your case you need to pass code2.replace('\\x', '').strip('"') to unhexlify . You can use eval and probably will, but consider this Security of Python's eval() on untrusted strings? for future choices.在您的情况下,您需要将code2.replace('\\x', '').strip('"')传递给unhexlify 。您可以使用eval并且可能会使用,但请考虑Python 的 eval() 在不受信任的字符串上的安全性?为未来的选择。

print eval(code2) should do the job. print eval(code2)应该可以完成这项工作。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM