python 2.4 的内置函数 bin() 的向后移植

发布于 2024-09-29 17:36:14 字数 121 浏览 3 评论 0原文

我编写了一个使用内置函数 bin() 的程序,但这个函数是 Python 2.6 版本中的新函数,我也想在 Python 2.4 和 2.5 版本中运行这个应用程序。

2.4 是否有一些 bin() 向后移植?

I wrote a program that uses builtin function bin(), but this function is new in Python version 2.6 and I would like to run this application also in Python versions 2.4 and 2.5.

Is there some backport of bin() for 2.4?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不奢求什么 2024-10-06 17:36:14

您可以尝试此版本(信用致原作者):

def bin(x):
    """
    bin(number) -> string

    Stringifies an int or long in base 2.
    """
    if x < 0: 
        return '-' + bin(-x)
    out = []
    if x == 0: 
        out.append('0')
    while x > 0:
        out.append('01'[x & 1])
        x >>= 1
        pass
    try: 
        return '0b' + ''.join(reversed(out))
    except NameError, ne2: 
        out.reverse()
    return '0b' + ''.join(out)

You can try this version (credit goes to the original author):

def bin(x):
    """
    bin(number) -> string

    Stringifies an int or long in base 2.
    """
    if x < 0: 
        return '-' + bin(-x)
    out = []
    if x == 0: 
        out.append('0')
    while x > 0:
        out.append('01'[x & 1])
        x >>= 1
        pass
    try: 
        return '0b' + ''.join(reversed(out))
    except NameError, ne2: 
        out.reverse()
    return '0b' + ''.join(out)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文