Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. What I'd like to achieve is a print statement that instead of :08b would take individual length like

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?

like image 666
po.pe Avatar asked Feb 17 '26 20:02

po.pe


1 Answers

You may first prepare the format string (because it is just a string, after all) and then use it for formatting the CRC:

crc = 23534
format = "CRC -> {{:0{:d}b}}".format((len(hex(crc)) - 2)*4)
#'CRC -> {:016b}'
format.format(crc)
#'CRC -> 0101101111101110'
like image 194
DYZ Avatar answered Feb 20 '26 08:02

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!