I want to display the number
0x40000000
as
01000000 00000000 00000000 00000000
with the leading 0 and formatting above
I want to display the number
0x40000000
as
01000000 00000000 00000000 00000000
with the leading 0 and formatting above
Maybe not the most flexible way, but:
>>> 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'
Umm, couldn't post earlier as my broadband was down, but slightly more flexible version...
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))
bits = format(num, '032b'). You could get the padding with pad = -8 * (-num.bit_length() // 8), which uses floor division to round up to a multiple of 8.xrange over the copied/zipped iterator in this case. Based on the calculated pad value, I had something like this in mind: bits = '{0:0{1}b}'.format(num, pad).This will handle arbitrarily large positive numbers:
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)
Output:
01000000 00000000 00000000 00000000
01000000 00000000 00000000 00000000 01000000 00000000 00000000 00000000