在给定字符串的 python 中进行基本转换

Base convert in python given a string

在PHP中,给定一个字符串值(由字符分隔的整数),我们可以计算它的整数表示:

$hashable = "123A123"; // notice "A" delim
$hash_int = base_convert($hashable, 11, 10);
echo $hash_int;

输出

2151042

它很有用,因为对于大范围的字符串(当然是短字符串),结果是唯一的。我在我的应用程序中使用它来生成 ID。

我们如何在 python 中进行相同的转换?是否可以为 PHP 和 python 中的相同字符串生成相等的整数?

也许首先我们需要取 hash int of hashable string 然后转换整数的基数我们这样做?

先前建议的方法对于二进制和许多其他转换将失败,这将从 2 到 36 的任何基数和 return 0 对于无效字符串,根据 php implementation,php 实现不会忽略输出中的字母,除非您为基数提供无效输入,然后它会尝试仅查找数字并进行转换,因此您也不能 return 一个 int ,并且会在输出中得到字母:

def to_base(n, bse):
    digs = "0123456789abcdefghijklmnopqrstuvwxyz"
    tmp = []
    while n:
        n, i = divmod(n, bse)
        tmp.append(digs[i])
    return "".join(tmp[::-1])



def chng_frm_base(s, frm_bse, to_bse):
    if to_bse < 2 or to_bse > 36 or frm_bse < 2 or frm_bse > 36:
        raise ValueError("bases must be between 2-36")
    try:
        return to_base(int(s, frm_bse), to_bse)
    except ValueError:
        try:
            n = int("".join([ch for ch in s if ch.isdigit()]),frm_bse)
            return to_base(n, to_bse)
        except ValueError:
            return 0

输出:

In [13]: chng_frm_base("123A123", 11, 10)
Out[13]: '2151042'

In [14]: chng_frm_base("123A123", 11, 8)
Out[14]: '10151202'

In [15]: chng_frm_base("123A123", 11, 2)
Out[15]: '1000001101001010000010'

In [16]: chng_frm_base("123A123", 11, 35)
Out[16]: '1f5xc'

In [17]: chng_frm_base("123A123", 11, 1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-9776e0abca26> in <module>()
----> 1 chng_frm_base("123A123", 11, 1)

<ipython-input-2-9c00d800545d> in chng_frm_base(s, frm_bse, to_bse)
     10 def chng_frm_base(s, frm_bse, to_bse):
     11     if to_bse < 2 or to_bse > 36 or frm_bse < 2 or frm_bse > 36:
---> 12         raise ValueError("bases must be between 2-36")
     13     try:
     14         return (to_base(int(s, frm_bse), to_bse))

ValueError: bases must be between 2-36

In [18]: chng_frm_base("hello world!", 10, 2)
Out[18]: 0

如果您 运行 使用 php 的相同示例输出所有相同的值。