简体   繁体   中英

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

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

This will give a response of 16 bytes, an example being:

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

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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