Peretz
Peretz

Reputation: 1126

File is not decoded properly

I have a file encoded in a strange pattern. For example,

Char (1 byte) | Integer (4 bytes) | Double (8 bytes) | etc...

So far, I wrote the code below, but I have not been able to figure out why still shows garbage in the screen. Any help will be greatly appreciated.

BRK_File = 'commands.BRK'
input = open(BRK_File, "rb")

rev = input.read(1)
filesize = input.read(4)
highpoint = input.read(8)
which = input.read(1)

print 'Revision: ', rev 
print 'File size: ', filesize
print 'High point: ', highpoint
print 'Which: ', which

while True
    opcode = input.read(1)
    print 'Opcode: ', opcode
    if opcode = 120:
         break
    elif
        #other opcodes

Upvotes: 5

Views: 201

Answers (2)

NPE
NPE

Reputation: 500227

read() returns a string, which you need to decode to get the binary data. You could use the struct module to do the decoding.

Something along the following lines should do the trick:

import struct
...
fmt = 'cid' # char, int, double
data = input.read(struct.calcsize(fmt))
rev, filesize, highpoint = struct.unpack(fmt, data)

You may have to deal with endianness issues, but struct makes that pretty easy.

Upvotes: 6

Falmarri
Falmarri

Reputation: 48569

It would be helpful to show the contents of the file, as well as the "garbage" that it's outputting.

input.read() returns a string, so you have to convert what you're reading to the type that you want. I suggest looking into the struct module.

Upvotes: 0

Related Questions