print out binary representation of c type in python

前端 未结 1 852
时光取名叫无心
时光取名叫无心 2021-01-18 19:38

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

相关标签:
1条回答
  • 2021-01-18 20:24

    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
    
    0 讨论(0)
提交回复
热议问题