Skip to content

Instantly share code, notes, and snippets.

@theikkila
Last active November 4, 2015 15:14
Show Gist options
  • Save theikkila/6fef38a6ce4ba7a18d8a to your computer and use it in GitHub Desktop.
Save theikkila/6fef38a6ce4ba7a18d8a to your computer and use it in GitHub Desktop.
Dec -> base27
function checkletter (s) {
lcount = 26; // 26 letters
var i = 0;
var csum = s.split('').reduce(function(sm, c, idx) {
var n = c.charCodeAt(0)-65;
if (idx % 2 == 0) {
return sm + n;
} else {
return sm + n*2;
}
}, 0);
var check = lcount - (csum % lcount);
return String.fromCharCode(check+64);
}
function base27_to_dec_with_check(b) {
var b_string = b.toUpperCase();
b = b_string.split('');
var base = 26; // 26 letters
var cl = b.pop();
if (cl !== checkletter(b.join(''))) {
throw new Error("Invalid checksum!");
}
return b.reverse().reduce(function (dec, c, idx) {
return dec + (c.charCodeAt(0) - 65) * Math.pow(base, idx);
}, 0);
}
function dec_to_base27_with_check(n) {
var base = 26;
var s = "";
while (n != 0) {
var r = n % base;
s = String.fromCharCode(r+65) + s;
n = (n / base) >> 0;
}
l = checkletter(s);
return (s + l).toUpperCase();
}
def checkletter(s):
"""Calculate checkletter with Luhn algorithm https://en.wikipedia.org/wiki/Luhn_algorithm"""
digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sm = 0
i = 0
for x in s:
if i%2==0:
sm += digits.index(x)
else:
sm += digits.index(x)*2
i += 1
check = len(digits) - (sm % len(digits))
return digits[check-1]
def dec_to_base27_with_check(n):
"""convert positive decimal integer to base27 code + checkletter"""
digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
base = len(digits)
s = ""
while 1:
r = n % base
s = digits[r] + s
n = n / base
if n == 0:
break
l = checkletter(s)
return (s + l).upper()
def base27_to_dec_with_check(b):
"""convert base27 code with checkletter to decimal integer"""
b = b.upper()
digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
base = len(digits)
b_without_checkletter = b[:-1].upper()
l = checkletter(b_without_checkletter)
if l != b[-1]:
raise ArithmeticError("Checksum is incorrect!")
i = 0
dec = 0
for c in b_without_checkletter[::-1]:
dec += digits.index(c)*(base**i)
i+=1
return dec
print dec_to_base27_with_check(123987)
print base27_to_dec_with_check("HBKTU")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment