python on 回风舞雪 https://huifeng.me/categories/python/ Recent content in python on 回风舞雪 Hugo -- gohugo.io en Fri, 26 Jul 2019 11:50:00 +0800 Binary I/O operation https://huifeng.me/posts/binary-io-operation/ Fri, 26 Jul 2019 11:50:00 +0800 https://huifeng.me/posts/binary-io-operation/ I coped with character type coversion to let it looks like c type, and search bytes from *.dll to modify it. so, there is sth I learned and written down here. # Binary I/O operation Define! def hex_read(filepath: str) -> bytearray: if os.path.isfile(filepath): with open(filepath, 'rb') as f: data = bytearray(f.read()) return data Usage: dll_data = hex_read('D:\\test\\test.dll') Find bytes and replace it: index_start = dll_data.find(b'\x85\x69\xf0\x7f') index_end = index_start + 100 if index_start != -1: data_old = dll_data[index_start:index_end] data_new = replacebytes # replacebytes is the content you want to replace dll_data_new = dll_data.replace(data_old, data_new) with open('D:\\test\\test.dll', 'wb') as f: f.write(dll_data_new) Hex byte string int coversion https://huifeng.me/posts/hex-b-str-int-switch-in-python/ Fri, 26 Jul 2019 09:56:00 +0800 https://huifeng.me/posts/hex-b-str-int-switch-in-python/ Reference: https://docs.python.org/zh-cn/3/library/stdtypes.html https://docs.python.org/zh-cn/3/library/struct.html # Python Types Coversion hey, there are some usefull features below, I will update at intervals: bit_length() New in version 3.1: In [73]: n = -37 In [74]: bin(n) Out[74]: '-0b100101' In [75]: n.bit_length() Out[75]: 6 hex to int: In [59]: int('0x22357', 16) Out[59]: 140119 int to hex: In [32]: hex(141128) Out[32]: '0x22748' packed binary data to int: In [70]: struct.unpack("I", b'\x57\x23\x02\x00') Out[70]: (140119,) In [71]: type(struct.unpack("I", b'\x57\x23\x02\x00')) Out[71]: tuple In [72]: struct.unpack("I", b'\x57\x23\x02\x00')[0] Out[72]: 140119 what is param “I”? Read More about struct int to packed binary data: