長い URL をエンコードおよびデコードするプログラムを作成しました。Encode は n 文字を取り、36 ビットの文字列を出力します。デコードは 36 ビットの文字列を取り、長い文字列を出力します。
print(decode(encode(1234567890)))
'1234567890'
つまり、基本的には、36 ビット文字列をランダム化し、逆にデコードするものです。疑似乱数ジェネレーターを使用して、シードされた PRNG のプロパティを可逆にし、数値の不変プロパティを使用して PRNG をシードする方法はありますか。
私はこのコードの断片を知っています。これらが役立つかもしれません。
def ls1b( x ):
"""Return least significant bit of x that is a one. (Assume x >= 0.)"""
return x & -x
と
def bitson( x ):
"""Return the number of one bits in x. (Assume x >= 0.)"""
count = 0
while x != 0:
x &= ~ls1b( x )
count += 1
return count
これが私のエンコードとデコードです。
def token (n):
if n < 10:
return chr( ord( '0' ) + (n) )
if n in range (10, 36):
return chr( ord( 'A' ) - 10 + (n))
if n in range (37, 62):
return chr( ord( 'a' ) - 36 + (n))
if n is 62:
return '-'
if n is 63:
return '+'
def encode (n):
a = n // 1 % 64
b = n // 64 % 64
c = n // 64 ** 2 % 64
d = n // 64 ** 3 % 64
e = n // 64 ** 4 % 64
f = n // 64 ** 5 % 64
return (token(a) + token(b) + token(c) + token(d) + token(e) + token(f))
def tokend (d):
x = ord(d)
if 48 <= x <= 57:
return x - ord('0')
if 65 <= x <= 90:
return x - ord('A') + 10
if 97 <= x <= 122:
return x - ord('a') + 36
if x is 43:
return ('62')
if x is 45:
return ('63')
def decode(code, base=64):
if base>64:
return 'error: too few symbols'
code=str(code)
o=0
e=0
for i in code:
o=o+detoken(i)*base**e
e=e+1
while len(str(o))<6:
o='0'+str(o)
return o