Last active
December 18, 2015 23:08
-
-
Save walkingice/5859462 to your computer and use it in GitHub Desktop.
A python script to convert number into different decimal. use "num.py [NUM]". NUM could be 100, 0x100, 0b100
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
#!/usr/bin/python | |
import sys | |
import re | |
reHex = re.compile(r"0x[\da-fA-F]+$") # match hex: 0x1100 | |
reBin = re.compile(r"0b[01]+$") # match binary: 0b1100 | |
reDec = re.compile(r"^\d+$") # match deciman: 1100 | |
def usage(): | |
print "\nusage:" | |
print "\t" + sys.argv[0] + " <Num>" | |
print "\t<num> could be 0x1100, 1100 or 0b1100\n" | |
''' | |
Split string into Array by length. | |
for seq='aaabbbccc', length=4 | |
it returns ['aaab', 'bccc'] | |
''' | |
def split_len(seq, length): | |
return [seq[i:i+length] for i in range(0, len(seq), length)] | |
def split_and_join(word, prepend='', j='.', split=4): | |
l = len(word) | |
# when split=4, 'f' gap is 3, 'foo' gap is 1 | |
# 'foob' gap is 0. to know how many '0' to prepend. | |
gap = (split - (l % split)) % split | |
filled = word.zfill( l + gap) | |
split = split_len(filled, split) | |
return prepend + j.join(split) | |
def convert(word, decimal): | |
print "[", word , "]" | |
print "->\t", decimal, | |
print "\t", split_and_join(hex(decimal)[2:],'0x'), | |
print "\t", split_and_join(bin(decimal)[2:],'0b') | |
print "" | |
def process(word): | |
decimal = 0 | |
if reHex.match(word): | |
decimal = int(word, 0) | |
elif reBin.match(word): | |
decimal = int(word, 2) | |
elif reDec.match(word): | |
decimal = int(word, 0) | |
else: | |
print "Not match: " + word | |
print "should be '0x1100' '1100' or '0b1100'" | |
return | |
convert(word, decimal) | |
def untilExit(): | |
while 1: | |
try: | |
line = sys.stdin.readline().strip('\r\n').split() | |
except KeyboardInterrupt: | |
break | |
if not line: | |
break | |
for word in line: | |
process(word) | |
def go(): | |
for x in sys.argv[1:]: | |
process(x) | |
if __name__ == "__main__": | |
if len(sys.argv) > 1 and sys.argv[1] == '-h': | |
usage() | |
else: | |
go() | |
untilExit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment