tantek çelik's newbase60 in python and java
Jan 19, 2010
i've been coding a small project in my free time and i had to develop a simple algorithm that is similar to base60 encoding to create shorter values. it was a nice coincidence that i saw tantek çelik also developed something similar algorithm called NewBase60. if you wonder who tantek çelik is just wikipedia him.anyway, here are the python and java versions of his algorithm.
def numtosxg(n):
s = ''
CHARACTERS = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz'
if not isinstance(n, (int, long)) or n == 0:
return '0'
while n > 0:
n, i = divmod(n, 60)
s = CHARACTERS[i] + s
return s
def numtosxgf(n, f):
s = numtosxg(n)
if not isinstance(f, (int, long)):
f = 1
f -= len(s)
while f > 0:
s = '0' + s
f -= 1
return s
and the java version
String numtosxg(int n) {
StringBuilder s = new StringBuilder();
final String CHARACTERS = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz";
if(n == 0) return "0";
while(n > 0) {
int remainder = n % 60;
s.append(CHARACTERS.charAt(remainder));
n = (n - remainder) / 60;
}
return s.reverse().toString();
}
String numtosxgf(int n, int f) {
StringBuilder s = new StringBuilder(numtosxg(n));
f -= s.length();
while(f > 0) {
s.append("0");
f--;
}
return s.reverse().toString();
}
int sxgtonum(String s) {
int n = 0;
int j = s.length();
for(int i = 0; i < j; i++) {
int c = (int) s.charAt(i);
if(c >= 48 && c <= 57) c -= 48;
else if (c >= 65 && c <= 72) c -=55;
else if (c == 73 || c == 108) c = 1;
else if (c >= 74 && c <= 78) c -= 56;
else if (c == 79) c = 0;
else if (c >= 80 && c <= 90) c -= 57;
else if (c == 95) c = 34;
else if (c >= 97 && c <= 107) c -= 62;
else if (c >= 109 && c <= 122) c -= 63;
else c = 0;
n = 60 * n + c;
}
return n;
}
maybe i should create a github repository for these snippets. anyway, i hope you find these useful. feel free to use them.