Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2.7
- ''' NumberMessage.py by The Pig in Minecraft
- (http://ookiepigster.tumblr.com/ - https://twitter.com/OokiePigster)
- This program is released in the public domain. You may do whatever you want
- with it. '''
- import sys
- import base64
- HELP = '''{} [Options]
- -t <Message> --to <Message> Converts the specified message to a number.
- -f <Number> --from <Number> Converts the number back to a string.
- -x --hex Switches to hexadecimal mode.
- -o --oct Switches to octal mode.
- -b --bin Switches to binary mode.
- -d --dec Switches to decimal mode (default).
- -F=<File> --file=<File> Loads data from the specified filename. If
- <File> is ommited or '-', it defaults to stdin.
- -h --help Prints this help.'''
- BASE_FORMATS = {2: 'b', 8: 'o', 10: '', 16: 'X'}
- def ToNumber(Str):
- Str = Str.replace('\x00', '').strip()
- if not Str:
- return 0
- Hex = base64.b16encode(Str)
- return int(Hex, 16)
- def FromNumber(Num):
- if not Num:
- return ''
- Hex = format(Num, 'X')
- return base64.b16decode(Hex)
- def _MainToNumber(Msg, Base):
- return format(ToNumber(Msg), BASE_FORMATS[Base])
- def _MainFromNumber(Num, Base):
- return FromNumber(int(Num, Base))
- def _MainDo(Arg, Mode, Base):
- if Mode == 'To':
- return _MainToNumber(Arg, Base)
- elif Mode == 'From':
- return _MainFromNumber(Arg, Base)
- else:
- raise ValueError
- def _ToFile(File):
- if File in (None, '-'):
- return sys.stdin
- elif hasattr(File, 'read'):
- return File
- elif isinstance(File, basestring):
- return open(File)
- else:
- raise TypeError
- def Main(argv):
- if len(argv) <= 1:
- print HELP.format(argv[0])
- return
- Mode = None
- Base = 10
- DoubleDash = False
- for I in argv[1:]:
- if DoubleDash:
- print _MainDo(Arg, Mode, Base)
- continue
- if '=' in I and I.startswith('-'):
- Pos = I.find('=')
- Arg = I[:Pos]
- Value = I[Pos + 1:]
- else:
- Arg = I
- Value = None
- if Arg in('-t', '--to'):
- Mode = 'To'
- elif Arg in ('-f', '--from'):
- Mode = 'From'
- elif Arg in ('-x', '--hex'):
- Base = 16
- elif Arg in ('-o', '--oct'):
- Base = 8
- elif Arg in ('-b', '--bin'):
- Base = 2
- elif Arg in ('-d', '--dec'):
- Base = 10
- elif Arg in ('-h', '--help'):
- print HELP.format(argv[0])
- elif Arg in ('-F', '--file'):
- print _MainDo(_ToFile(Value).read(), Mode, Base)
- elif Arg == '--':
- DoubleDash = True
- elif Arg.startswith('-'):
- sys.stdout.write('Invalid argument: {}\n{}\n'.format(Arg, HELP.format(argv[0])))
- return 1
- elif Mode in ('To', 'From', None):
- print _MainDo(Arg, Mode, Base)
- else:
- raise Exception('?!')
- if __name__ == '__main__':
- sys.exit(Main(sys.argv) or 0)
Add Comment
Please, Sign In to add comment