In this example...
temp = 0b110
print temp
temp.str(temp).zfill(8)
print temp
the output is...
0b110
0000b110
How do I add the zeros so I see an eight bit binary output, 0b00000110?
In this example...
temp = 0b110
print temp
temp.str(temp).zfill(8)
print temp
the output is...
0b110
0000b110
How do I add the zeros so I see an eight bit binary output, 0b00000110?
If you're calling the bin
function, or using a format string with #b
, or whatever, the resulting string has 0b
on the front, so it's too late to zero-fill, unless you want to do something hacky like pull it off, zero-fill to n-2 characters, then put it back on.
But if you just do the zero-filling before (or while) adding the prefix rather than after, it's easy. For example:
>>> temp = 0b110
>>> format(temp, '#010b')
'0b00000110'
The docs explain this in detail, but the short version is:
#
means "alternate form", which gives me the 0b
prefix0
means zero-pad10
means width of 10 (including the 0b
)b
means binary