Python: Choose number of bits to represent binary number
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)