Trying to output hex data as readable text in Python 3.6

1

I am trying to read hex values from specific offsets in a file, and then show that as normal text. Upon reading the data from the file and saving it to a variable named uName, and then printing it, this is what I get:

Card name is: b'\x95\xdc\x00'

Here's the code:

cardPath = str(input("Enter card path: "))
print("Card name is: ", end="")
with open(cardPath, "rb+") as f:
    f.seek(0x00000042)
    uName = f.read(3)
    print(uName)

How can remove the 'b' I am getting at the beginning? And how can I remove the '\x'es so that b'\x95\xdc\x00' becomes 95dc00? If I can do that, then I guess I can convert it to text using binascii.

I am sorry if my mistake is really really stupid because I don't have much experience with Python.

python-3.x
asked on Stack Overflow Apr 8, 2018 by Andy_519 • edited Apr 8, 2018 by Andy_519

1 Answer

0

Those string started with b in python is a byte string. Usually, you can use decode() or str(byte_string,'UTF-8) to decode the byte string(i.e. the string start with b') to string.

EXAMPLE

str(b'\x70\x79\x74\x68\x6F\x6E','UTF-8')
'python'

b'\x70\x79\x74\x68\x6F\x6E'.decode()
'python'

However, for your case, it raised an UnicodeDecodeError during decoding.

str(b'\x95\xdc\x00','UTF-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 0: invalid start byte

I guess you need to find out the encoding for your file and then specify it when you open the file, like below:

open("u.item", encoding="THE_ENCODING_YOU_FOUND")
answered on Stack Overflow Apr 8, 2018 by R.yan • edited Apr 8, 2018 by R.yan

User contributions licensed under CC BY-SA 3.0