【发布时间】:2026-01-26 03:15:01
【问题描述】:
我已经编写了一个程序来对长 URL 进行编码和解码。编码将占用 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
【问题讨论】:
-
您是否要像 tinyurl 一样缩短 URL?另外,为什么解码输出“36位”而编码需要“6个字符”?
-
如果我理解正确,您正在尝试做一个可逆哈希函数,对吧?或者可能是压缩功能之类的东西?
-
我已经成功地缩短了 URL。而且,对不起,我并不是说它只编码 6 个字符。它可以编码任意长度的字符。我想要做的是随机化编码和解码操作的输出。
-
我只是把它们弄混了。我希望编辑有所帮助。
标签: python url encoding random decode