3

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?

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I tried the "same" approach with string concatenation like format = "CRC -> {{:0"+str((len(hex(crc)) - 2)*4)+"b}}" but that didn't work. Yours does!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.