基于How Do You Express Binary Literals in Python的构建,我正在考虑以明智,直观的方式来编程以基本-2形式显示整数的栗子。这是我想出的最好的,但我想用一个更好的算法取代它,或者至少有一个应该有尖叫快的性能。使用Python的基-2(二进制)表示法
def num_bin(N, places=8):
def bit_at_p(N, p):
''' find the bit at place p for number n '''
two_p = 1 << p # 2^p, using bitshift, will have exactly one
# bit set, at place p
x = N & two_p # binary composition, will be one where *both* numbers
# have a 1 at that bit. this can only happen
# at position p. will yield two_p if N has a 1 at
# bit p
return int(x > 0)
bits = (bit_at_p(N,x) for x in xrange(places))
return "".join((str(x) for x in bits))
# or, more consisely
# return "".join([str(int((N & 1 << x)>0)) for x in xrange(places)])
感谢您或多或少的完整答案,这是使用2.6或3.0 bin()函数n :) – 2008-10-21 16:29:27