Velocity Reviews > Re: integer to binary 0-padded

# Re: integer to binary 0-padded

Olivier LEMAIRE
Guest
Posts: n/a

 06-15-2011
You're right, I use Python 2.6.6

John S
Guest
Posts: n/a

 06-17-2011
On Jun 15, 9:33*am, Olivier LEMAIRE <m.olivier.lema...@gmail.com>
wrote:
> You're right, I use Python 2.6.6

This works great in 2.6.5 and later (and probably earlier). You just
have to number your placeholders. The first set of braces formats i
(your value), the second set specifies the field with (i.e., :

>>> for i in xrange(10):

.... print "{0:0{1}b}".format(i,
....
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001

jmfauth
Guest
Posts: n/a

 06-18-2011
>>> '{:+#0{}b}'.format(255, 1 + 2 + 16)
+0b0000000011111111
>>> '{:+#0{}b}'.format(-255, 1 + 2 + 16)

-0b0000000011111111
>>>
>>> eval('{:+#0{}b}'.format(255, 1 + 2 + 16))

255
>>> eval('{:+#0{}b}'.format(-255, 1 + 2 + 16))

-255
>>>

jmf

Steven D'Aprano
Guest
Posts: n/a

 06-18-2011
On Fri, 17 Jun 2011 23:14:09 -0700, jmfauth wrote:

>>>> '{:+#0{}b}'.format(255, 1 + 2 + 16)

> +0b0000000011111111
>>>> '{:+#0{}b}'.format(-255, 1 + 2 + 16)

> -0b0000000011111111
>>>>
>>>> eval('{:+#0{}b}'.format(255, 1 + 2 + 16))

> 255
>>>> eval('{:+#0{}b}'.format(-255, 1 + 2 + 16))

> -255

Is this a question? Or did you just decide to share some code?

Please leave enough context so that readers can understand what you are

--
Steven