import os; import re; #################################################################### # USAGE: INTEGER = CreateHexFile(FILENAME, [CONTENT]) # This function creates a file and writes bytes in binary mode. # The bytes have to be provided as a string or list of # hexadecimal numbers. Each byte must be formatted as # a 2-digit hexadecimal number. # # The function returns 1 on success or 0 on error. # # The following example creates a file and writes "ABC" # NULL-terminated string into the file: # # CreateHexFile("testing.txt", " 41 42 43 00 ") # def CreateHexFile(FileName, Content = []): try: # Convert Content to a string and then # remove everything except hexadecimal digits: Content = re.sub("[^a-fA-F0-9]+", "", repr(Content)) # Line up the hexadecimal numbers in pairs # and convert them to integers: Content = map(lambda n: int(n, 16), re.findall('..', Content)) # Create the file and open for writing in binary mode: myfile = open(FileName, "wb") # Detect Python version by doing a simple division and # looking for the remainder. Python 2 always drops the # remainder when doing a division, so if the result # of 1/2 is zero, then the interpreter is Python 2. Python2 = (1 / 2) == 0 # Convert the list of integers to bytes # and write them to the file: if Python2: myfile.write("".join(map(chr, Content))) else: myfile.write(bytearray(Content)) myfile.close() except IOError: return 0 return 1 #CreateHexFile("C:\\DESKTOP\\TESTING456.BIN", " A0 01 CB C3 30 40 50 60 70 80 90 A0 B0 C0 D0 E0 F0 FF 41 42 0D") CreateHexFile("ASCIIPY.BIN", ["CB", "C3", "00", "9A", "80", "41", "0D"])