-1

Python_Cookbook_3rd_Edition

6.12. Reading Nested and Variable-Sized Binary Structures

import struct
import itertools

def write_polys(filename, polys):
    # Determine bounding box
    flattened = list(itertools.chain(*polys))
    min_x = min(x for x, y in flattened)
    max_x = max(x for x, y in flattened)
    min_y = min(y for x, y in flattened)
    max_y = max(y for x, y in flattened)
    with open(filename, 'wb') as f:
        f.write(struct.pack('<iddddi', 0x1234,
                            min_x, min_y,
                            max_x, max_y,
                            len(polys)))
        for poly in polys:
            size = len(poly) * struct.calcsize('<dd')
            f.write(struct.pack('<i', size + 4))
            for pt in poly:
                f.write(struct.pack('<dd', *pt))

Why use f.write(struct.pack('<i', size + 4)) size+4

I think just f.write(struct.pack('<i', size))is ok

ShijieHuo
  • 1
  • 1

1 Answers1

0

In the book in the figure right before the code, it shows how polygon records are encoded. The first field is an int whose value is "Record length including length (N bytes)". Since this record length is written as a 4-byte i integer, 4 is being added to size of all the points (pairs of X,Y coordinates) comprising the polygon.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • but if i change the code to " f.write(struct.pack(' – ShijieHuo Feb 15 '20 at 15:58
  • That's because the code in the `read_polys()` function that almost immediately follows `write_polys()` divides the length value read, `pbytes`, by `16` when it's read back, so you're right about it not mattering. However, there's another `read_polys()` function presented later on (page 212) in the same section which makes use of a class method utility named `SizedRecord.from_file()` to read polygons, and it has the keyword argument `includes_size=True`. That function reads the data in a different manner and in a way where whether the `+ 4` was used or not could matter. – martineau Feb 15 '20 at 18:27