Skip to content

Instantly share code, notes, and snippets.

@guyskk
Last active August 26, 2024 07:25
Show Gist options
  • Save guyskk/98621a9785bd88cf2b4e804978950122 to your computer and use it in GitHub Desktop.
Save guyskk/98621a9785bd88cf2b4e804978950122 to your computer and use it in GitHub Desktop.
bindiff: Binary file diff
#!/usr/bin/env python
"""
Binary file diff
Usage:
bindiff <FILE> <FILE>
Install:
curl -L https://gist.githubusercontent.com/guyskk/98621a9785bd88cf2b4e804978950122/raw/efc200c6e45c3ef503249cf3b151fb8a1f5b75cb/bindiff.py -o bindiff && chmod +x bindiff
"""
import io
import sys
def _to_hex(value):
if sys.version_info[0] <= 2:
return ''.join('{:02x}'.format(ord(x)) for x in value).upper()
else:
return value.hex().upper()
def main():
try:
f1 = io.open(sys.argv[1], 'rb')
f2 = io.open(sys.argv[2], 'rb')
except IndexError:
print(__doc__.strip())
sys.exit(1)
except IOError as ex:
print(ex)
sys.exit(1)
chunk_size = 40
offset = 0
max_diff = 100
num_diff = 0
try:
while True:
d1 = f1.read(chunk_size)
d2 = f2.read(chunk_size)
if d1 != d2:
hex1 = _to_hex(d1)
hex2 = _to_hex(d2)
diff = ''.join(x == y and ' ' or '^' for x, y in zip(hex1, hex2))
pad = ' ' * (len(str(offset)) + 2)
print('{}> {}\n{}{}\n{}{}'.format(offset, hex1, pad, diff, pad, hex2))
num_diff += 1
if num_diff >= max_diff:
print('Too many differences, skip...')
break
if d1 == b'' or d2 == b'':
break
offset += chunk_size
finally:
f1.close()
f2.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment