我编写了一个使用内置函数bin()的程序,但是这个函数在Python 2.6版本中是新的,我想在Python版本2.4和2.5中运行这个应用程序。
2.4(
)是否存在bin()的一些反向移植?答案 0 :(得分:6)
您可以尝试this version(归功于原作者):
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)