0

I have a hex file with extension .brt and having hex values in the range 00 - FF. I want to parse the file and print byte by byte value in the command prompt.

I tried the below line of code:

file = open("file.brt", encoding='utf-8')
data = file.read()

this gives me error as:

Exception has occurred: UnicodeDecodeError
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I understand the error is because the value is more than 128. then i tried with utf-16, this gives some random value. then i have tried with the below line of code :

file = open("file.brt", encoding='ANSI')
data = file.read()
for line in data:
    for char in line:
        print(char.encode('utf-8').hex())

The above code is parsing the data but printing some random value if the hex value is more than 128. for example if the hex value is FF, then it prints c3bf

  • 2
    `encoding='utf-8` means you're expecting *characters* in the file (UTF-8 encoded). Is that appropriate? What's the source of the .brt file? It might be a binary format, so you should `open` in binary mode ('b'), see [docs](https://docs.python.org/3/library/functions.html#open). – FObersteiner Jul 28 '21 at 06:26
  • What do you call *a hex file*? Can you open it with a text editor (notepad, notepad++, vi, etc.) and see hex codes, or do you have to open it with a binary editor to see the hex codes **of raw bytes**? – Serge Ballesta Jul 28 '21 at 06:31

1 Answers1

0

You could try to open the file in Binary Mode, by changing the open-line to open('file', 'b'). Then you can process your file in Hex-values.

ductTapeIsMagic
  • 113
  • 1
  • 8