[英]print out binary representation of c type in python
我在C
/ C++
具有以下数字,例如0x0202020202ULL
,我想以二进制形式1000000010000000100000001000000010
打印出来。
能否请你帮忙?
您可以结合使用slicing(或str.rstrip
), int
和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'
更新:
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')
输出:
0010 0000 0010 0000 0010 0000 0010 0000 0010
0001 0000
0001 0000 0001 0000 0001 0000
1111 1111 1111
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.