You are not logged in.

#1 2006-02-25 17:05:28

Riklaunim
Member
Registered: 2005-04-09
Posts: 106
Website

Binary files in Python, code snippet in Java to Python

I'm trying to get data out of a game file (ITM/Baldurs Gate http://iesdp.gibberlings3.net/ieformats/itm_v1.htm). Some of variables can't be read directly (like dword) (won't show the data it should).

A java based NearInfinity converts binary dword data in this way:

  public static int convertInt(byte buffer[], int offset)
  {
    int value = 0;
    for (int i = 3; i >= 0; i--)
      value = (value << 8) | (buffer[offset + i] & 0xFF);
    return value;
  }

Now, how Python code would look like? I've checked binascii module with no luck.

Offline

#2 2006-02-26 12:48:32

arooaroo
Member
From: London, UK
Registered: 2005-01-13
Posts: 1,268
Website

Re: Binary files in Python, code snippet in Java to Python

Use the 'b' flag when opening your file.

myFile = open("something.dat", "rb")

data = myFile.read()

Now you can iterate over each byte and do whatever you want.

Offline

#3 2006-02-26 15:30:28

Riklaunim
Member
Registered: 2005-04-09
Posts: 106
Website

Re: Binary files in Python, code snippet in Java to Python

I have

plik = open('bow08.itm', 'rb')
try:
        tekst = plik.read()
finally:
        plik.close()

# char array - works
print tekst[0x0004:0x0004+4]
# resref - works
print tekst[0x003a:0x003a+8]

#dword
print tekst[0x004c:0x004c+4]

and the dword (and few other variables) won't show anything (will output binary something), the java snippet in my first post from NearInfinity converts that binary code into a normal data smile

Offline

#4 2006-02-27 20:51:21

alterkacker
Member
From: Peoples Republic of Boulder
Registered: 2005-01-08
Posts: 52

Re: Binary files in Python, code snippet in Java to Python

You need to use the 'int()' function to convert the character string to an integer.

Offline

#5 2006-02-28 18:54:56

Riklaunim
Member
Registered: 2005-04-09
Posts: 106
Website

Re: Binary files in Python, code snippet in Java to Python

it isn't a string, it's something binary wink ValueError: invalid literal for int():

Offline

#6 2006-02-28 23:21:35

alterkacker
Member
From: Peoples Republic of Boulder
Registered: 2005-01-08
Posts: 52

Re: Binary files in Python, code snippet in Java to Python

Sorry for my hasty (and wrong) reply! I think you want to look at the 'unpack' function in the 'struct' module.

Offline

Board footer

Powered by FluxBB