Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct.pack(!i, 10) result is "00 00 00 0d 0a" on Windows

I found an odd problem with Python's struct.pack("!i", 10) on a Windows system. I get the buffer and save it in to a file, but the result is

 00 00 00 0d 0a

where on Mac OSX, the result is

00 00 00 0a

What does the 0d mean?

When I pass 11 instead of 10, the result is 00 00 00 0b. So I think when I pass 10, the result should be 00 00 00 0a.

If I want to get 00 00 00 0a when I pass 10, what should I do instead?

like image 946
oneRain Avatar asked Mar 14 '23 12:03

oneRain


1 Answers

What does the 0d mean?

It means '\r'

If I want to get 00 00 00 0a when I pass 10, what should I do instead?

Try to open file in binary mode:

with open('file', 'wb') as f:
    f.write(struct.pack("!i", 10))

When you try write '\n' (0a) to a file on Windows and the file is opened in text mode, Python adds '\r' before '\n'.

From documentation:

In text mode, the default is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n on reading and \n back to platform-specific line endings on writing. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

like image 121
Aleksandr Kovalev Avatar answered Mar 23 '23 07:03

Aleksandr Kovalev