-
Notifications
You must be signed in to change notification settings - Fork 0
/
changebase
executable file
·103 lines (94 loc) · 2.75 KB
/
changebase
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python
from sys import argv, stdin
import math
from time import sleep
numerals = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
#https://en.wikipedia.org/wiki/Base64
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def badbase():
print("Please try again: choose a base between 2 and 64")
exit(1)
def badchar():
print("Invalid chars.\n" +
"Valid chars are 0-9, A-Z, a-z, _-=+/#\n" +
"up to the index allowed by the chosen number,\n" +
"ie, only up to F for base16\n")
exit(1)
def to_10(num, from_base):
num = num.replace('=', '')
num = num.replace('#', '')
if from_base == "10":
return(num)
else:
to_10 = 0
degree = len(num) - 1
cursor = 0
#build a polynomial, and sum it :-)
try:
while degree >= 0:
if from_base <= 63:
coeff = numerals[0:from_base].index(num[cursor])
elif from_base == 64:
coeff = base64.index(num[cursor])
to_10 = to_10 + coeff * (from_base ** degree)
degree = degree - 1
cursor = cursor + 1
except IndexError:
badchar()
except ValueError:
badchar()
return(to_10)
def to_n(num, to_base):
#num is base10
try:
rem = int(num)
except ValueError:
print("Invalid chars.\n" +
"Valid chars are 0-9, A-Z, a-z, _-=+/#")
exit(1)
ans = ""
try:
degree = int(math.log(rem, to_base))
except ValueError as e:
if num == 0:
print("0")
exit(0)
else:
print("Value error: {}".format(e))
exit(1)
#find a polynomial, and write it down
while degree >= 0:
coeff = rem / (to_base ** degree)
if to_base <= 63:
ans = ans + numerals[coeff]
elif to_base == 64:
ans = ans + base64[coeff]
rem = rem - (coeff * to_base ** degree)
degree = degree - 1
return(ans)
def start(num, from_base, to_base):
b10num = to_10(num, from_base)
print(to_n(b10num, to_base))
if len(argv) < 4:
print("usage:\n" +
"{} <number_in_some_base or - for stdin> -f <from_base> -t <to_base>".format(argv[0]))
else:
n = argv[1]
if n == '-':
n = stdin.readline().rstrip()
i = 3
for arg in argv[2:]:
if arg == '-f':
f=int(argv[i])
if f not in range(2,65):
badbase()
if arg == '-t':
t=int(argv[i])
if t not in range(2,65):
badbase()
i = i+1
if not 'f' in vars():
f=10
if not 't' in vars():
t=10
start(n, f, t)