FRC
FRC

Reputation: 485

open bin file and convert ascii to hex

I want to open some data from a bin file

import io
data=io.open('bpsk_2m_b11.rd16','rb').read()
print (data)

But there appear to be some ASCII symbols, e.g. (i mean '{' and 'k','w' )

b'\xde{\x1d\x86\xa0\x81kw\xbc\x8a'

I'm fine with the whole formating thing but how can I replace those ASCII symbols with hex? Or should I use some other mode to read this file?

Upvotes: 1

Views: 1106

Answers (1)

phihag
phihag

Reputation: 287905

Everything is working fine, b'{' is just another way of writing b'\x7b':

>>> b'{' == b'\x7b'
True

You can create a character string of only escapes with the following helper method:

import binascii
def to_byte_escapes(b):
   return ''.join('\\x' + binascii.hexlify(byte) for byte in b)

Then you'll get:

>>> print(to_byte_escapes(b'\xde{\x1d\x86\xa0\x81kw\xbc\x8a'))
\xde\x7b\x1d\x86\xa0\x81\x6b\x77\xbc\x8a

Upvotes: 1

Related Questions