在python中打印出c类型的二进制表示形式

在python中打印出c类型的二进制表示形式,python,c,Python,C,我在C/C++中有以下数字,例如,0x020202ull,我想以二进制形式打印出来100000010000001000001000000010 你能帮忙吗 您可以使用切片(或str.rstrip)、int和格式的组合 >>> inp = '0x0202020202UL' >>> format(int(inp[:-2], 16), 'b') '1000000010000000100000001000000010' # Using `str.rstrip`, Th

我在
C
/
C++
中有以下数字,例如,
0x020202ull
,我想以二进制形式打印出来
100000010000001000001000000010


你能帮忙吗

您可以使用切片(或
str.rstrip
)、
int
格式的组合

>>> 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
输出:

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

美好的仅仅是一个小技巧,如何将它分成4位,用空格分隔,比如
10 0000 0010 0000 0010 0000 0010 0000 0010 0000 0010
?仍然不正确。例如,0x10将产生错误的result@Eugene使用rstrip版本,我得到了
0x10
'0001 0000'
。切片版本仅适用于无符号long,而
rstrip
版本适用于任何十六进制。我实际上是指ULL。我看不出C在这里的相关性。您也可以在Python中使用
0x020202