Re: How to modify the data in a binary file?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?utf-8?q?C=C3=A9dric_Lucantis?=

    Re: How to modify the data in a binary file?

    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:

    Source code: Lib/struct.py This module converts between Python values and C structs represented as Python bytes objects. Compact format strings describe the intended conversions to/from Python valu...


    --
    Cédric Lucantis
Working...