#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0

    Trying to write binary data to a file


    I'm converting some code I have written in VB .NET to Python and I've hit a problem when I need to write out a binary file. The file is going to be used by an external program so it needs to be formatted specifically. In .NET that isn't much of a problem since it can write all sorts of number types, but I'm fairly new to Python and it isn't quite designed for that sort of thing it seems.

    I need to write out in this format:
    4 characters (header)
    2 shorts (16 bit signed integers)
    X double values
    4 characters (same as header)

    I think I can handle everything except for the short values. I think this:
    Code:
      
    bw.Write(Chr(52))                     bw.Write(Chr(0))                     bw.Write(Chr(0))                     
    bw.Write(Chr(0))
    Converts to this:
    Code:
                
    writeBinaryFile.write('%c' % 52)             writeBinaryFile.write('%c' % 0)             writeBinaryFile.write('%c' % 0)             writeBinaryFile.write('%c' % 0)
    I'm assuming I can write the double values directly but I still need to test that.

    I'm not sure about the short values though. Any ideas?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,900
    Rep Power
    481
    I think you need the struct module.
    http://docs.python.org/3/library/struct.html



    Character Byte order Size Alignment
    @ native native native
    = native standard none
    < little-endian standard none
    > big-endian standard none
    ! network (= big-endian) standard none



    Format C Type Python type Standard size Notes
    x pad byte no value
    c char bytes of length 1 1
    b signed char integer 1 (1),(3)
    B unsigned char integer 1 (3)
    ? _Bool bool 1 (1)
    h short integer 2 (3)
    H unsigned short integer 2 (3)
    i int integer 4 (3)
    I unsigned int integer 4 (3)
    l long integer 4 (3)
    L unsigned long integer 4 (3)
    q long long integer 8 (2), (3)
    Q unsigned long long integer 8 (2), (3)
    n ssize_t integer (4)
    N size_t integer (4)
    f float float 4 (5)
    d double float 8 (5)
    s char[] bytes
    p char[] bytes
    P void * integer (6)
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0
    Thanks.

IMN logo majestic logo threadwatch logo seochat tools logo