Last active
August 29, 2015 14:01
-
-
Save michael34435/75a95c59e7f7c2e9847c to your computer and use it in GitHub Desktop.
hex decoder/encoder by python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys,os,gzip | |
def is_gzip(filename): | |
f = open(filename, 'rb') | |
if f.read(2).encode('hex') == '1f8b': | |
return True | |
pass | |
return False | |
pass | |
def to_btye(filename,zip_mode): | |
file_static = open(filename, 'rb') | |
if zip_mode: | |
file_zip = gzip.open('compressed_'+os.path.splitext(filename)[0],'wb') | |
elif ~zip_mode: | |
file_zip = open('compressed_'+os.path.splitext(filename)[0],'wb') | |
pass | |
while True: | |
byte = file_static.read(1) | |
if byte == '': | |
break | |
else: | |
try: | |
string = str(ord(byte)) | |
file_zip.write((('0'*(4-len(string)))+string).decode('hex')) | |
pass | |
except Exception, e: | |
print e | |
pass | |
pass | |
file_static.close() | |
file_zip.close() | |
is_gzip('compressed_'+os.path.splitext(filename)[0]) | |
pass | |
def to_file(filename,unzip_mode): | |
if unzip_mode == 1: | |
file_compressed = open(filename, 'rb') | |
elif unzip_mode == 2: | |
file_compressed = gzip.open(filename, 'rb') | |
elif unzip_mode == 3: | |
if is_gzip(filename): | |
file_compressed = gzip.open(filename, 'rb') | |
else: | |
file_compressed = open(filename, 'rb') | |
pass | |
pass | |
file_real = open('test_'+os.path.splitext(filename)[0],'wb') | |
while True: | |
byte = file_compressed.read(2) | |
if byte == '': | |
break | |
else: | |
try: | |
file_real.write(chr(int(str(byte).encode('hex')))) | |
pass | |
except Exception, e: | |
print e | |
pass | |
pass | |
file_compressed.close() | |
file_real.close() | |
pass | |
if __name__ == '__main__': | |
try: | |
flag = sys.argv[1] | |
if flag == '-f': | |
to_file(sys.argv[2],1) | |
elif flag == '-b': | |
to_btye(sys.argv[2],False) | |
elif flag == '-fz': | |
to_file(sys.argv[2],2) | |
elif flag == '-bz': | |
to_btye(sys.argv[2],True) | |
elif flag == '-fa': | |
to_file(sys.argv[2],3) | |
else: | |
to_btye(sys.argv[1],False) | |
pass | |
pass | |
except Exception, e: | |
print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment