Created
March 19, 2019 10:56
-
-
Save MerleLiuKun/1e8b125d249fd2581423f562c9ad29d7 to your computer and use it in GitHub Desktop.
simple binary conversion for numbers and letters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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