基於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