Dave
Dave

Reputation: 4328

convert hexadecimal to bytes in python

I want to display the number

0x40000000

as

01000000 00000000 00000000 00000000

with the leading 0 and formatting above

Upvotes: 0

Views: 195

Answers (2)

martineau
martineau

Reputation: 123521

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

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142216

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))

Upvotes: 2

Related Questions