birchroad / node-jspack

JavaScript library to pack primitives to octet arrays, packaged for NodeJS
http://code.google.com/p/jspack/
BSD 3-Clause "New" or "Revised" License
15 stars 12 forks source link

Different lengths compared to Python's `struct.calcsize` #13

Open mikew opened 5 years ago

mikew commented 5 years ago

For a string like BBBBBBBh, jspack and Python give different sizes:

FMT="BBBBBBBh"
$ node -e "console.log(require('jspack').jspack.CalcLength('$FMT'))"
9
$ python -c "import struct; print(struct.calcsize('$FMT'))"
10
dgarciabriseno commented 1 year ago

This is expected behavior.

Per the readme:

Character | Byte Order
----------------------------------
    <     | little-endian
    >     | big-endian
    !     | network (= big-endian)

If the first character is not one of these, "!" is assumed.

This is different than Python's default choice

If the first character is not one of these, '@' is assumed.

The difference between these is that '@' is native byte order. System dependent. And it's not supported by jspack. The python docs also say

Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.

Padding i being added for the h because it sites at byte 7. When using the native format, Python wants to put the short at byte 8.

>>> struct.calcsize('BBBBBBBh')
10
>>> struct.calcsize('<BBBBBBBh')
9
>>> struct.calcsize('!BBBBBBBh')
9