Convert int to ASCII and back in Python

前端 未结 5 2111
庸人自扰
庸人自扰 2020-12-04 06:08

I\'m working on making a URL shortener for my site, and my current plan (I\'m open to suggestions) is to use a node ID to generate the shortened URL. So, in theory, node 26

5条回答
  •  清歌不尽
    2020-12-04 06:28

    If multiple characters are bound inside a single integer/long, as was my issue:

    s = '0123456789'
    nchars = len(s)
    # string to int or long. Type depends on nchars
    x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
    # int or long to string
    ''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))
    

    Yields '0123456789' and x = 227581098929683594426425L

提交回复
热议问题