简体   繁体   English

Python打印二进制数字格式

[英]Python print formatting of binary number

I have a binary number I need to print including the leading zeros. 我有一个我需要打印的二进制数字,包括前导零。 So far I do this with: 到目前为止,我这样做:

print("CRC -> {:08b}".format(crc)

But this crc could have different sizes. 但是这个crc可能有不同的尺寸。 What I'd like to achieve is a print statement that instead of :08b would take individual length like 我想要实现的是一个打印声明,而不是:08b将采取个人长度

crc_len = (len(hex(crc))-2)*4

But how would my print then need to look, how can I do conditional formatting depending on crc_len ? 但是我的打印需要怎样才能看,我如何根据crc_len进行条件格式化呢?

You may first prepare the format string (because it is just a string, after all) and then use it for formatting the CRC: 您可以先准备格式字符串(因为它毕竟只是一个字符串),然后用它来格式化CRC:

crc = 23534
format = "CRC -> {{:0{:d}b}}".format((len(hex(crc)) - 2)*4)
#'CRC -> {:016b}'
format.format(crc)
#'CRC -> 0101101111101110'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM