Skip to content

Instantly share code, notes, and snippets.

@mrtnvgr
Created November 25, 2024 14:43
Show Gist options
  • Save mrtnvgr/f1c27cfd34a6d77ec8fa34ef477b1614 to your computer and use it in GitHub Desktop.
Save mrtnvgr/f1c27cfd34a6d77ec8fa34ef477b1614 to your computer and use it in GitHub Desktop.
Binary patcher
from io import BytesIO
class Patch():
def __init__(self, offset: int, original: str, new: str):
self.offset = offset
self.original = bytes.fromhex(original)
self.new = bytes.fromhex(new)
def __str__(self):
return f"[\"{self.original.hex()}\" -> \"{self.new.hex()}\" (at {self.offset})]"
def apply_patches(data: bytes, patches: list[Patch]):
f = BytesIO(data)
for patch in patches:
f.seek(patch.offset)
data = f.read(len(patch.original))
if data != patch.original:
raise Exception(f"Failed to apply a patch: {patch}")
f.seek(patch.offset)
f.write(patch.new)
f.seek(0)
return f.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment