繁体   English   中英

将 int 转换为 ASCII 并返回 Python

[英]Convert int to ASCII and back in Python

我正在为我的网站制作 URL 缩短器,我目前的计划(我愿意接受建议)是使用节点 ID 来生成缩短的 URL。 因此,理论上,节点 26 可能是short.com/z ,节点 1 可能是short.com/a ,节点 52 可能是short.com/Z ,节点 104 可能是short.com/ZZ 当用户转到该 URL 时,我需要反转该过程(显然)。

我可以想到一些关于 go 的笨拙方法,但我猜还有更好的方法。 有什么建议么?

ASCII 到整数:

ord('a')

给出97

回到一个字符串:

  • 在 Python2 中: str(unichr(97))
  • 在 Python3 中: chr(97)

给出'a'

>>> ord("a")
97
>>> chr(97)
'a'

如果多个字符绑定在单个整数/长整数内,就像我的问题:

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))

产量'0123456789'x = 227581098929683594426425L

BASE58 编码 URL 怎么样? 就像 flickr 一样。

# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' 
url = ''
while node_id >= 58:
    div, mod = divmod(node_id, 58)
    url = BASE58[mod] + url
    node_id = int(div)

return 'http://short.com/%s' % BASE58[node_id] + url

把它变成一个数字也没什么大不了的。

显然我迟到了,只是想分享一个我经常使用的片段。

/**
 * 62 = 26 + 26 +10
 *
 * @param id
 * @return
 */
public String base62(long id) {
    StringBuilder sb = new StringBuilder();
    while (id >= 62) {
        int remainer = (int) (id % 62);
        id = id / 62;
        sb.append(index2char(remainer));
    }
    sb.append(index2char(id));

    return sb.reverse().toString();
}

public long reverseBase62(String s) {
    long r = 0;
    for (int i = 0; i < s.length(); i++) {
        r = r * 62;
        int index = char2index(s.charAt(i));
        if (index == -1) {
            throw new IllegalArgumentException(
                String.format("[%s] is in malformation, should only contain 0~9, a~z, A~Z", s));
        }
        r += index;
    }

    return r;
}
private char index2char(long index) {
    if (index < 10) {
        return (char) ('0' + index);
    }
    if (index < 36) {
        return (char) ('a' + index - 10);
    }
    return (char) ('A' + index - 36);
}



private int char2index(char c) {
    if ('0' <= c && c <= '9') {
        return c - '0';
    }
    if ('a' <= c && c <= 'z') {
        return c - 'a' + 10;
    }
    if ('A' <= c && c <= 'Z') {
        return c - 'A' + 36;
    }
    return -1;
}

使用hex(id)[2:]int(urlpart, 16) 还有其他选择。 base32 编码您的 id 也可以工作,但我不知道有任何库可以在 Python 中进行 base32 编码。

显然,带有base64 模块的Python 2.4 中引入了 base32 编码器。 您可以尝试使用b32encodeb32decode 你应该为casefoldmap01选项给b32decode提供True以防人们写下你缩短的 URL。

其实,我收回。 我仍然认为 base32 编码是一个好主意,但该模块对于 URL 缩短的情况没有用。 您可以查看模块中的实现,并针对这种特定情况创建自己的实现。 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM