Skip to content

Instantly share code, notes, and snippets.

@guyskk
Last active March 30, 2020 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guyskk/98621a9785bd88cf2b4e804978950122 to your computer and use it in GitHub Desktop.
Save guyskk/98621a9785bd88cf2b4e804978950122 to your computer and use it in GitHub Desktop.
Binary file diff
#!/usr/bin/env python
"""
Binary file diff
Usage:
bindiff <FILE> <FILE>
Install:
curl -L https://gist.githubusercontent.com/guyskk/98621a9785bd88cf2b4e804978950122/raw/b933874153efe018538ff2050cb27d1a948246e2/bindiff.py -o bindiff && chmod +x bindiff
"""
import sys
import io
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
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))
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