0

I want to display the number

0x40000000

as

01000000 00000000 00000000 00000000

with the leading 0 and formatting above

2
  • You mean you want to convert hexadecimal to binary. Commented Nov 21, 2012 at 13:45
  • with byte formatting I think Commented Nov 21, 2012 at 13:54

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

You could use 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.
@eryksun I updated the answer slightly using something I had open and was playing with, but broadband went down - it appears to work, still not 100% sure if I'm happy, but oh well...
I prefer 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).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.