Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7693

Re: integer to binary 0-padded

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: integer to binary 0-padded
Followup-To comp.lang.python
Date 2011-06-15 14:54 +0200
Organization None
Message-ID <itaa1d$a57$1@solani.org> (permalink)
References <5c29244e-41fe-4f19-80d1-83a2169b9cc9@glegroupsg2000goo.googlegroups.com>

Followups directed to: comp.lang.python

Show all headers | View raw


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'

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

integer to binary 0-padded Olivier LEMAIRE <m.olivier.lemaire@gmail.com> - 2011-06-15 05:29 -0700
  Re: integer to binary 0-padded Daniel Rentz <daniel.rentz@gmx.de> - 2011-06-15 14:33 +0200
    Re: integer to binary 0-padded Tim Chase <python.list@tim.thechases.com> - 2011-06-15 08:13 -0500
  Re: integer to binary 0-padded Chris Angelico <rosuav@gmail.com> - 2011-06-15 22:48 +1000
  Re: integer to binary 0-padded Peter Otten <__peter__@web.de> - 2011-06-15 14:54 +0200

csiph-web