您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:20:25 python 字数 1370 阅读 456 来源 www.jb51.cc/python

我在C/C++中有以下编号,例如,0x0202020202ULL,我想以二进制形式1000000010000000100000001000000010打印出来. 能否请你帮忙? 您可以使用切片(或str.rstrip),int和format的组合. >>> inp = '0x0202020202UL' >>> format(int(inp[:-2], 16), 'b') '100000001000

概述

能否请你帮忙?

>>> 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'),'b')
'1000000010000000100000001000000010'

更新:

from itertools import islice
def formatted_bin(inp):
   output = format(int(inp.rstrip('UL'),'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

总结

以上是编程之家为你收集整理的在python中打印出c类型的二进制表示全部内容,希望文章能够帮你解决在python中打印出c类型的二进制表示所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶