Is there a built-in function to replace multiple bytes? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Is there a built-in function to replace multiple bytes? (/thread-2186.html) |
Is there a built-in function to replace multiple bytes? - Raptor88 - Feb-24-2017 I'm learning Python 3.6. I figured out how to use the find() function to find a multiple hex byte string in a byte variable as follows: with open("test 18.vf", "rb") as binaryFile: byteData = bytearray(binaryFile.read()) mx = 0 while mx != -1: mx = byteData.find(b'\x2A\x07\x3B\x1C\x14', mx) if mx != -1: Do somethingIs there a built-in function to change consecutive bytes in "byteData" that looks similar to the find function above? If not, any suggestions on the easiest way to replace 7 consecutive bytes? I won't be inserting any bytes. Just replacing 7 consecutive bytes elsewhere in "byteData". Thanks. RE: Is there a built-in function to replace multiple bytes? - Larz60+ - Feb-24-2017 Untested, but this should work: replace: mx = byteData.find(b'\x2A\x07\x3B\x1C\x14', mx)with: bytedata=butedata.replace(b'\x2A\x07\x3B\x1C\x14', b'New value here') RE: Is there a built-in function to replace multiple bytes? - Raptor88 - Feb-24-2017 (Feb-24-2017, 08:01 PM)Larz60+ Wrote: Untested, but this should work: Thanks Larz60+. I won't know the bytes to be replaced as they could vary depending on the user's setup. I neglected to say that I will be replacing the 7 bytes based on the index value of "mx". For example: 1. Search for the 5 byte string. 2. If found, mx = index of first found byte. 3. Add a value to mx to skip bytes. Like mx += 52. 4. Replace 7 bytes starting from the current index value of mx. 5. Repeat steps 1-4 until the end of "byteData" signified by mx == -1. Sorry for not being more through in my initial post. Thanks. RE: Is there a built-in function to replace multiple bytes? - zivoni - Feb-24-2017 If you want to replace 7 bytes from given index mx, you can do byteData[mx : mx+7] = 1, 2, 3, 4, 5, 6, 7bytearray is mutable, so it will work. And if you want these bytes replaced with different number of bytes, you can use .insert() method or del byteData[index1: index2]. RE: Is there a built-in function to replace multiple bytes? - Raptor88 - Feb-25-2017 (Feb-24-2017, 11:53 PM)zivoni Wrote: If you want to replace 7 bytes from given index mx, you can do Hi zivoni, So simple, so easy, so clean. Works perfectly, So thanks! Raptor88 |