簡體   English   中英

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

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

我有一個用於mifare讀取器的十六進制命令字符串,其中一個命令示例是

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

這將給出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 \\ t \\ n \\ t \\ x0f \\ x03 \\ r \\x0eÿ'

我試圖通過使用以下方式更改其格式

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ÿ'

同樣通過更改字符串的編碼,但這也不會在解碼后提供原始字符串。 我想要得到的結果是

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

這樣,Mifare閱讀器可以在需要時將此字符串用作數據寫入新標簽。 任何幫助,將不勝感激

我認為您遇到的問題是python試圖將您的數據解釋為UTF-8文本,但這是原始數據,因此不可打印。 我要做的是數據進行十六進制編碼以將其打印在文件中,並在讀取時對十六進制進行解碼。

就像是:

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)

接着

# test
>>> x == s
True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM