简体   繁体   English

Python 3:在打印和格式化时保持十六进制命令字符串完整

[英]Python 3 : keep string of hex commands intact while printing and formatting

I have a string of hex commands for a mifare reader, an example of one of the commands being 我有一个用于mifare读取器的十六进制命令字符串,其中一个命令示例是

'\\xE0\\x03\\x06\\x01\\x00' '\\ xE0 \\ x03 \\ x06 \\ x01 \\ x00'

This will give a response of 16 bytes, an example being: 这将给出16个字节的响应,示例如下:

'\\x0F\\x02\\x02\\x07\\x05\\x06\\x07\\x01\\x09\\x0A\\x09\\x0F\\x03\\x0D\\x0E\\xFF' '\\ x0F \\ x02 \\ x02 \\ x07 \\ x05 \\ x06 \\ x07 \\ x01 \\ x09 \\ x0A \\ x09 \\ x0F \\ x03 \\ x0D \\ x0E \\ xFF'

I need to store these values in a text document but whenever I try to make the hex commands into a string, the string always changes and doesn't keep its original format, and this string will turn into 我需要将这些值存储在文本文档中,但是每当我尝试将十六进制命令转换为字符串时,该字符串将始终更改且不保持其原始格式,并且该字符串将变为

'\\x0f\\x02\\x02\\x07\\x05\\x06\\x07\\x01\\t\\n\\t\\x0f\\x03\\r\\x0eÿ' '\\ x0f \\ x02 \\ x02 \\ x07 \\ x05 \\ x06 \\ x07 \\ x01 \\ t \\ n \\ t \\ x0f \\ x03 \\ r \\x0eÿ'

I have tried to change the formatting of this, by using 我试图通过使用以下方式更改其格式

d = d.encode()
print("".join("\\x{:02x}".format(c) for c in d))
# Result
'\x0f\x02\x02\x07\x05\x06\x07\x01\t\n\t\x0f\x03\r\x0eÿ'

Also by changing the encoding of the string but this also doesn't give the original string as a result after decoding. 同样通过更改字符串的编码,但这也不会在解码后提供原始字符串。 What I would like to get as a result would be 我想要得到的结果是

'\x0F\x02\x02\x07\x05\x06\x07\x01\x09\x0A\x09\x0F\x03\x0D\x0E\xFF'

This is so the mifare reader can use this string as data to write to a new tag if necessary. 这样,Mifare阅读器可以在需要时将此字符串用作数据写入新标签。 Any help would be appreciated 任何帮助,将不胜感激

I think the problem you are experiencing is that python is trying to interpret your data as UTF-8 text, but it is raw data, so it is not printable. 我认为您遇到的问题是python试图将您的数据解释为UTF-8文本,但这是原始数据,因此不可打印。 What I would do is hex encode the data to print it in the file, and hex decode it back when reading. 我要做的是数据进行十六进制编码以将其打印在文件中,并在读取时对十六进制进行解码。

Something like: 就像是:

import binascii # see [1]
s = b'\xE0\x03\x06\x01\x00' # tell python that it is binary data
# write in file encoded as hex text
with open('file.txt','w') as f:
     # hexlify() returns a binary string containing ascii characters
     # you need to convert it to regular string to avoid an exception in write()
     f.write(str(binascii.hexlify(s),'ascii'))
# read back as hex text
with open('file.txt', 'r') as f:
     ss=f.read()
# hex decode
x=binascii.unhexlify(ss)

And then 接着

# test
>>> x == s
True

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

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