I am trying to write an hex string into a file using python 2.7 so that when opened with HxD I can retrieve the same hex values. The following code works fine on multiple input strings, but when the string contains '0A' the writing is not working correctly.
import binascii
s = "0ABD"
f = open("output","w")
f.write(binascii.a2b_hex(s))
f.close()
After that open the file using HxD or online https://hexed.it/, you will find that '0D' is added before each '0A'. I am reading these generated files using vb.net and still I am getting more bytes than expected.
CodePudding user response:
You are opening the file for writing in text mode, so newlines are converted to use system convention. In the case of Windows 0A
or '\n'
gets converted to 0D 0A
or '\r\n'
.
From the python's documentation for open() (emphasis added):
If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert
'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append'b'
to the mode value to open the file in binary mode, which will improve portability.
Open the file in binary mode.
f = open("output", "wb")