codegeschrei
codegeschrei

Reputation: 37

Missing zeros when using .format() to make an integer to a binary

So I wanted to convert an integer to a binary in Python. And I found this really nice explanation and used it in my program. Since I later had to work with the binary I had some issues and saw that some curious things happen with the format.

When having '{0:08b}'.format(6) in my program or entering it into the shell I get: '00000110'. But when I try the same thing with 16 and 32 bit the zeros are not shown and I can't seem to use them. Like:

>>> '{0:16b}'.format(6)
'             110'
>>> '{0:32b}'.format(6)
'                             110'

So I wondered why it is like that (I found another solution for myself and my program but it's still annoying me to not know why it is like this!)

If this question was already asked and answered I'm sorry. I googled for it and tried to find a question like mine here with no success.

Upvotes: 2

Views: 4506

Answers (1)

BrenBarn
BrenBarn

Reputation: 251458

The 0 in 08b is part of the format specification. See the documentation here. If you want zero padding, do '{0:016b}'.format(6) or '{0:032b}'.format(6).

Upvotes: 6

Related Questions