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

    Join Date
    May 2005
    Posts
    3
    Rep Power
    0

    struct: Hl vs lH


    do you know what this program prints?

    import struct
    print struct.calcsize("Hl")
    print struct.calcsize("lH")

    8
    6

  2. #2
  3. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    I'm on another computer right now that doesn't have Python installed, but what exactly are you asking?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2005
    Posts
    3
    Rep Power
    0
    why these are different?
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65

    Smile


    You are supposed to send a format string, not just any string. Do a help('struct.calcsize') for more detail.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Dietrich, he has clearly read the docs, since he is using valid format strings.

    "Hl" is a struct with an unsigned short followed by a long integer.

    "lH" is a long integer followed by an unsigned short.

    The reason these structs are different sizes is because on most systems the elements of C structs are aligned to fall on word boundaries, for efficiency reasons. On systems with a 4-byte word length this will add padding bytes to force elements to start at offsets with a multiple of 4.

    So the first struct contains:

    * 2 byte unsigned short at offset 0
    * 2 padding bytes at offset 2
    * 4 bytes long int at offset 4

    total length = 8

    The second struct contains:

    * 4 bytes long int at offset 0
    * 2 byte unsigned short at offset 4

    Total length = 6

    However if you were to have a C array of the second struct then it would still allocate 8 bytes for each entry, since it would align each array entry on a 4-byte boundary.

    The results are completely machine dependent - a 64 bit processor will probably pad everything to 8 byte boundaries, resulting in even more padding bytes being added.

    Any good book on C programming will explain all this.

    Dave - The Developers' Coach

IMN logo majestic logo threadwatch logo seochat tools logo