24进制 编码实现



#coding: utf8


ALPHABET = 'abcdefghijkmnpqrstuvwxyz'
ALPH_VALUE={'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'m':11,'n':12,'p':13,
        'q':14,'r':15,'s':16,'t':17,'u':18,'v':19,'w':20,'x':21,'y':22,'z':23 }


def encode24( number ):
    print "in encode24 "
    if not isinstance(number, (int, long)):
        raise TypeError('number must be an integer')
    if number < 0:
        raise ValueError('number must be positive')


    base24 = ''


    while number:
        number, i = divmod(number, 24)
        base24 = ALPHABET[i] + base24
    
    return base24 or ALPHABET[0]


def decode24( coding24 ):
    #return int(coding24, 36) 
    #decimal = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]


    num = 0
    length = len(coding24)
    for i in range(0, length):
        num += ALPH_VALUE.get(coding24[i])* pow(24, length-1-i)


    return num


def check(coding24):
    check_tab = [13, 11, 7, 3]
    
    num = 0
    min_len = min(len(coding24), len(check_tab))
    
    for i in range(0, min_len):
        num += ALPH_VALUE.get(coding24[i]) * check_tab[i]
    num = num % 24


    check_alph = encode24(num)


    return check_alph


if __name__ == '__main__':
    for i in range(0,96):
        coding24 = encode24(i)
        number = decode24(coding24)
        print "coding24=%s, number=%d, check=%s" % (coding24, number, check(coding24) )
    
    print decoding24("aadz")


    print 




阅读更多
文章标签: 24进制 十进制
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭