如何对字符串进行Base36编码?

5 投票
4 回答
6537 浏览
提问于 2025-04-16 17:54

我在网上查了很久,但找不到解决办法。在Python、Ruby或Java中,怎么把这个字符串进行36进制编码:nOrG9Eh0uyeilM8Nnu5pTywj3935kW+5=

4 个回答

0

看起来维基百科上有一篇关于如何在Python中实现这个功能的文章:http://en.wikipedia.org/wiki/Base_36

1

我刚刚做了这个:

  static String encodeRootId(final String value) {
    try {
      final BigInteger bigInteger = new BigInteger(value.getBytes("UTF-8"));
      final String encoded = bigInteger.toString(Character.MAX_RADIX);

      //must encode the sign as well
      if (bigInteger.signum() < 0) {
        return 'n' + encoded.substring(1);
      } else {
        return 'p' + encoded;
      }
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("impossible");
    }
  }

把字符串的字节数组转换成大整数的方法有个缺点,就是需要手动处理可能出现的负号,虽然这看起来不太好,但算是个快速的解决办法。

而且在我的使用场景中,我不需要解码,性能也不是问题。

9

Ruby


转换为36进制:

s.unpack('H*')[0].to_i(16).to_s 36

从36进制转换:

[s36.to_i(36).to_s(16)].pack 'H*'

撰写回答