integer to binary 0-padded

Peter Otten __peter__ at web.de
Wed Jun 15 08:54:41 EDT 2011


Olivier LEMAIRE wrote:
> I've been looking for 2 days for a way to convert integer to binary number
> 0-padded, nothing... I need to get numbers converted with a defined number
> of bits. For example on 8 bits 2 = 00000010 I wrote the following:

> b = str(bin(number))[2:]

The result of bin() is already a string, no need to apply str().
> if len(b) !=size:
> b = (size-len(b))*"0"+b

b.zfill(size) can do that.
> Though, what do you think about it ?

Here's another way (requires Python 2.7):
>>> "{:0{}b}".format(42, 10)
'0000101010'


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /