0

我想显示号码

0x40000000

作为

01000000 00000000 00000000 00000000

前导 0 和上面的格式

4

2 回答 2

2

也许不是最灵活的方式,但是:

>>> num = 0x40000000
>>> bits = bin(num)[2:].zfill(32)
# '01000000000000000000000000000000'
>>> ' '.join(bits[i:i+8] for i in xrange(0, 32, 8))
'01000000 00000000 00000000 00000000'

嗯,因为我的宽带断了,不能早点发帖,但稍微灵活一点的版本......

def fmt_bin(num):
    bits = bin(num)[2:]
    blocks, rem = divmod(len(bits), 8)
    if rem:
        blocks +=1
    filled = bits.zfill(blocks * 8)
    return ' '.join(''.join(el) for el in zip(*[iter(filled)]*8))
于 2012-11-21T13:36:04.280 回答
1

这将处理任意大的正数:

def long2str(n):
    if n == 0:
        return '00000000'
    s = []
    while n > 0:
        s.append('{:08b}'.format(n & 255))
        n = n >> 8
    return ' '.join(s[::-1])

num = 0x40000000
bignum = 0x4000000040000000
print long2str(num)
print long2str(bignum)

输出:

01000000 00000000 00000000 00000000
01000000 00000000 00000000 00000000 01000000 00000000 00000000 00000000
于 2012-11-21T14:45:56.377 回答