2

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.

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

1 Comment

gosh... I always misread the whole thing because I thought one has to use two digits to represent the bits. >.< thank you and sorry for the trouble

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.