6

I have the following number in C/C++, for example, 0x0202020202ULL and I'd like to print it out in binary form 1000000010000000100000001000000010.

Could you please help?

2
  • I actually meant ULL. Commented Aug 12, 2013 at 1:39
  • I fail to see the relevance of C here. You can have 0x0202020202 in Python as well. Commented Aug 12, 2013 at 7:23

1 Answer 1

4

You can use a combination of slicing(or str.rstrip), int and format.

>>> inp = '0x0202020202UL'
>>> format(int(inp[:-2], 16), 'b')
'1000000010000000100000001000000010'
# Using `str.rstrip`, This will work for any hex, not just UL
>>> format(int(inp.rstrip('UL'), 16), 'b')
'1000000010000000100000001000000010'

Update:

from itertools import islice
def formatted_bin(inp):
   output = format(int(inp.rstrip('UL'), 16), 'b')
   le = len(output)
   m = le % 4
   padd = 4 - m if m != 0 else 0
   output  = output.zfill(le + padd)
   it = iter(output)
   return ' '.join(''.join(islice(it, 4)) for _ in xrange((le+padd)/4))

print formatted_bin('0x0202020202UL')
print formatted_bin('0x10')
print formatted_bin('0x101010')
print formatted_bin('0xfff')

output:

0010 0000 0010 0000 0010 0000 0010 0000 0010
0001 0000
0001 0000 0001 0000 0001 0000
1111 1111 1111
Sign up to request clarification or add additional context in comments.

3 Comments

nice. just a little trick, how to separate it into 4 bits separated by a space, like 10 0000 0010 0000 0010 0000 0010 0000 0010?
still not correct. for example ·0x10· would produce wrong result
@Eugene Using the rstrip version I got '0001 0000' for 0x10. The slicing version is for unsigned long only, while rstrip version will work for any hex.

Your Answer

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