integer to binary 0-padded
Chris Angelico
rosuav at gmail.com
Wed Jun 15 08:48:35 EDT 2011
On Wed, Jun 15, 2011 at 10:29 PM, Olivier LEMAIRE
<m.olivier.lemaire at gmail.com> wrote:
> b = str(bin(number))[2:]
> if len(b) !=size:
> b = (size-len(b))*"0"+b
You don't need the str() there as bin() already returns a number.
Here's a relatively trivial simplification - although it does make the
code more cryptic:
b = (size*"0"+bin(number)[2:])[-size:]
After typing this up, I saw Daniel's post, which is rather better. Go
with that one for zero-filling; mine's more general though, you can
pad with other tokens.
ChrisA
More information about the Python-list
mailing list