How to modify the data in a binary file?

Cédric Lucantis omer at no-log.org
Wed Jul 2 14:15:38 CEST 2008


Le Wednesday 02 July 2008 14:05:39 Jim Brown, vous avez écrit :
> Hi all, I'm a Python newbie, so please pardon me if my question may look a
> little silly. :)
>
> I want to modify a binary file p.data (which has some C-style "short"
> integers -- 16-bit integers) in such a way:
> The bit m and bit n of every "short int" si in the file are set to 1, and
> the left bits in si are not affected.
>
> I.e, for the first short int in the file, I think the code would be:
>
> import os
> f = os.open("/root/p.data", os.O_RDWR)
> str = os.read(f, 2)
>
> #assume the short int in str is 0x0102, and I want to change it to 0x8182
> (changing bit7 and bit15 to 1).
> #how to change the str into a short int variable si??
> ???
>
> si = (si & ~0x8080) | 0x8080
>

You can either do it by hand by splitting your string in chars and getting the 
bytes values with ord (described here: 
http://docs.python.org/lib/built-in-funcs.html) :

byte0 = ord(s[0])
byte1 = ord(s[1])
si = (byte0 << 8) | byte1 # or maybe the inverse ?

or use the struct module:

http://docs.python.org/lib/module-struct.html

-- 
Cédric Lucantis



More information about the Python-list mailing list