Skip to content

Instantly share code, notes, and snippets.

@h4sh5
Created April 5, 2020 15:02
Show Gist options
  • Save h4sh5/3e1c85cc5e08d9248527e1cc09c58e81 to your computer and use it in GitHub Desktop.
Save h4sh5/3e1c85cc5e08d9248527e1cc09c58e81 to your computer and use it in GitHub Desktop.
hex to string in python - also basic usage of getopt
#!/usr/bin/env python
import getopt
import sys
import binascii
def usage():
print("""%s [-oxd]
-x hex
-d decode
-b base64
""" % sys.argv[0])
try:
opts, args = getopt.getopt(sys.argv[1:], "dho:xb", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
decode = False
encoding = 0
for opt, arg in opts:
if opt == "-d":
decode = True
if opt == '-x':
encoding = "hex"
elif opt == "-h":
usage()
exit(0)
#print(decode, encoding)
string = raw_input()
while 1:
if decode:
try:
print string.decode("hex")
string = raw_input()
except ValueError:
exit("invalid hex")
except EOFError:
exit(0)
else:
print(string.encode('utf-8').hex())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment