Skip to content

Instantly share code, notes, and snippets.

@MerleLiuKun
Created March 19, 2019 10:56
Show Gist options
  • Save MerleLiuKun/1e8b125d249fd2581423f562c9ad29d7 to your computer and use it in GitHub Desktop.
Save MerleLiuKun/1e8b125d249fd2581423f562c9ad29d7 to your computer and use it in GitHub Desktop.
simple binary conversion for numbers and letters
# coding=utf-8
CONSTANT_BEGIN = 201416920417
CONSTANT_CHAR = 'JTXD9hz6SBqpINCrx5Memk1LO2ylcPYjFnwbd4tv3VW0aiRK8oGE7fuQgsAUHZ'
CONSTANT_LENGTH = len(CONSTANT_CHAR)
def encode_b64(num):
if not isinstance(num, (int, long)):
raise TypeError('Must int num')
if num <= 0:
raise ValueError('Must great than 0')
code_str = ''
source = num + CONSTANT_BEGIN
while source > 0:
code_str += CONSTANT_CHAR[source % CONSTANT_LENGTH]
source /= CONSTANT_LENGTH
return code_str[::-1].rjust(6, CONSTANT_CHAR[0])
def decode_b64(code_str):
res = 0
for idx in xrange(len(code_str)):
res *= CONSTANT_LENGTH
res += CONSTANT_CHAR.index(code_str[idx])
code_id = res - CONSTANT_BEGIN
if code_id >= 0:
return code_id
else:
raise ValueError('Code Error')
if __name__ == '__main__':
n = 1080
s = encode_b64(n)
n2 = decode_b64(s)
print(s, n2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment