0

How to read a hex file and convert it to plain text?
For example, this is my file user.dat.(For China mainland user.dat)

And here is what I have tried so far:

# -*- coding:utf-8 -*-
with open('user.dat','rb') as f:
    data = f.read()
print data

And the result is like this.Some is right,while some is not.

How to get the entire right content?

Camel
  • 19
  • 1
  • 4
  • Do you want to *convert it to plain text*? Or just print it out? – Remi Guan Oct 12 '15 at 12:24
  • Try just open it in `'r'` mode. – Remi Guan Oct 12 '15 at 13:01
  • Thanks,but just get the same result above. – Camel Oct 12 '15 at 13:04
  • Hmm...see [this](http://stackoverflow.com/a/11683394/5299236) question and [this](http://stackoverflow.com/questions/29547104/convertdecode-hex-string-to-ascii-or-any-other-understandable-format) question. – Remi Guan Oct 12 '15 at 13:09
  • And by the way, seems like that there're lots of Chinese and garbled in the decoded string. Could you upload the file for us download and try to convert it? – Remi Guan Oct 12 '15 at 13:13
  • I search on google and stackoverflow,but can not solve it.Many thanks to u! And i have upload my example file. Any suggestion? – Camel Oct 12 '15 at 14:03
  • No problem :) Let me check it. – Remi Guan Oct 12 '15 at 14:04
  • Unfortunately that I can't print any useful text. I could only get something like `���A�����`. But seems like you've nearly done it. Maybe these text are different encoding? – Remi Guan Oct 12 '15 at 14:25
  • That file is raw binary data, not hex. No hex decoding is needed. But it's not clear what you actually expect to get from the file: you said "some is right, while some is not", but you didn't say which parts you think are wrong, or what's wrong with them. So it's impossible for anyone to tell you what you should do with the data. – Wyzard Oct 12 '15 at 14:33
  • I got the file from my friend,as he can not read the content of it.The right part maybe is the character in Chinese.So i push this question.Any suggestion? – Camel Oct 13 '15 at 09:45

1 Answers1

0

just add this line of in your code, str.decode('hex') will decode string into plain text.

output = data.decode('hex')
print output

OK you have some error so try this...

import binascii
with open('user.dat', 'rb') as f:
    data = f.read()
print(binascii.hexlify(data))
Saket Mittal
  • 3,726
  • 3
  • 29
  • 49