I am curious as to how I can change the number of bits to represent a binary number. For example, say I want express decimal 1 to binary. I use:
bin(1) and get 0b1.
How can I get the return to say 0b01 or 0b001 or 0b0001 etc?
Use the Format String Syntax:
>>> format(1, '#04b')
'0b01'
>>> format(1, '#05b')
'0b001'
>>> format(1, '#06b')
'0b0001'
You can use str.zfill to pad the binary part:
def padded_bin(i, width):
s = bin(i)
return s[:2] + s[2:].zfill(width)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With