0

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?

A.S.
  • 101
  • 1
  • 1
  • That can't be your code. `temp.str` is going to be an `AttributeError`. Please give us a [mcve]. – abarnert Mar 25 '18 at 18:27
  • @RoryDaulton Yeah, I realized that in editing the comment to fix that it was also going to take more explanation, so I canceled, created an answer, and then it was too late to edit the comment, so I deleted it. – abarnert Mar 25 '18 at 18:35

1 Answers1

2

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 prefix
  • 0 means zero-pad
  • 10 means width of 10 (including the 0b)
  • b means binary
abarnert
  • 354,177
  • 51
  • 601
  • 671