Python Python When writing binary files, you can use the struct module st R U ct struct to bind data into structures and convert them into byte streams. To avoid unnecessary trouble caused by C C C byte alignment problems when reading binary byte streams, Py T H on Python Python str U C t struct The struct module is aligned according to the byte alignment mode of C C C by default.
However, it is not as simple as it seems. Python Python struct struct The byte alignment of the struct module fooled me all morning.
First, I wrote the binary in Py T ho N Python, and I tested Py T H o N Python to read the binary, and it tested fine, I didn’t have any problems, but when I wrote the C C C interface, Only to find that the data had been flawed. Python Python Python Python Pyt R U C t struct struct module
I’m going to use Py T H on Python Python is going to put in a bunch of h E a D E r Header Header,
struct header
{
long long a;
int b;
};
Copy the code
S truct struct struct module format string ‘q I’ ' qi' ‘qi’, in C C C C, Header Header Header should take up 16 16 16 bytes due to byte alignment, but in Py T H o N Python Python does not…
>>> import struct
>>> struct.calcsize('qi')
12
Copy the code
It’s 12, 12, 12 bytes, obviously no byte alignment… Then I tried it. iq' ‘IQ’, which surprised me again…
>>> struct.calcsize('iq')
16
Copy the code
You read that right, the bytes are actually aligned, 16, 16, 16 bytes. This wave of operation is hot…
Both methods were tested repeatedly with C, C, C, and the results were 16, 16, 16 bytes.
Python Python Python 2q' ‘2q’, mom doesn’t have to worry about byte alignment anymore.
But is it possible that different C C C compilers have different byte alignment for the two versions? I do not know, nor specific to test, after all, I am a person who does not understand.
By the way, if there is a big guy whose compiler does have different byte alignment results, please let me know what compiler is used so THAT I can avoid him…