| |
 Search this list this category for: (Advanced)

Mailing List Archive: Python: Python

# convert integer to binary

ekranawetter at utanet

May 2, 2003, 12:31 PM

Post #1 of 9 (3293 views)
 convert integer to binary
Hi all,

I couldn't find any function in Python to convert integers to binary
and vice versa, for example:

integer 16 = bin 10000, or
integer 15 = bin 1111
bin 11 = integer 3

ekranawetter [at] bmw

Thanks

fperez528 at yahoo

May 2, 2003, 1:13 PM

Post #2 of 9 (3221 views)
 convert integer to binary [In reply to]
ekranawetter-piber wrote:

> Hi all,
>
> I couldn't find any function in Python to convert integers to binary
> and vice versa, for example:
>
> integer 16 = bin 10000, or
> integer 15 = bin 1111
> bin 11 = integer 3

These are pulled from by bitbucket. I don't claim credit for them, as it's
quite possible that they are reworks of code I found on the net:

def base_repr (number, base = 2, padding = 0):
"""Return the representation of a number in any given base."""
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if number < base: \
return (padding - 1) * chars [0] + chars [int (number)]
max_exponent = int (math.log (number)/math.log (base))
max_power = long (base) ** max_exponent
base_repr (number - max_power * lead_digit, base, \

def binary_repr (number, max_length = 64):
"""Return the binary representation of the input number as a string.

This is more efficient than using base_repr with base 2.

This will only work reliably for relatively small numbers.
Increase the value of max_length if you think you're going
to use long integers."""

assert number < 2L << max_length
shifts = map (operator.rshift, max_length * [number], \
range (max_length - 1, -1, -1))
digits = map (operator.mod, shifts, max_length * [2])
if not digits.count (1): return 0
digits = digits [digits.index (1):]
return ''.join (map (repr, digits)).replace('L','')

def bin(i):
"""Return the binary representation of the input number as a string.

l = [.'0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
s = ''.join(map(lambda x: l[int(x, 16)], hex(i)[2:]))
if s[0] == '1' and i > 0:
s = '0000' + s
return s

>
> ekranawetter [at] bmw

Cheers,

f.

FBatista at uniFON

May 2, 2003, 1:17 PM

Post #3 of 9 (3199 views)
 convert integer to binary [In reply to]
This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.

------_=_NextPart_001_01C310E7.D8582150
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

One way can be this:

>>> def IntToBin(num):
... bin =3D ""
... while num:
... bin +=3D str(num%2)
... num /=3D 2
... return bin
...=20
>>> IntToBin(9)
'1001'
>>> IntToBin(127)
'1111111'

I just made it. Can it be optimized?=20

One way to optimize could be instead of add strings, just append in =
list,
and the return a "".join(str(list))

How can I easily test the speed of this?

Facundo

#- -----Mensaje original-----
#- De: ekranawetter [at] utanet [mailto:ekranawetter [at] utanet]
#- Enviado el: Viernes 2 de Mayo de 2003 4:31 PM
#- Para: python-list [at] python
#- Asunto: convert integer to binary
#-=20
#-=20
#- Hi all,
#-=20
#- I couldn't find any function in Python to convert integers to binary
#- and vice versa, for example:
#-=20
#- integer 16 =3D bin 10000, or=20
#- integer 15 =3D bin 1111
#- bin 11 =3D integer 3
#-=20
#- ekranawetter [at] bmw
#-=20
#- Thanks
#- --=20
#- http://mail.python.org/mailman/listinfo/python-list
#-=20

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . =
. . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . =
. . .
. . . . . . . . . . . . . . .

La informaci=F3n contenida en este mensaje y cualquier archivo anexo al =
mismo,
son para uso exclusivo del destinatario y pueden contener informaci=F3n
confidencial o propietaria, cuya divulgaci=F3n es sancionada por la =
ley.=20

Si Ud. No es uno de los destinatarios consignados o la persona =
responsable
de hacer llegar este mensaje a los destinatarios consignados, no est=E1
autorizado a divulgar, copiar, distribuir o retener informaci=F3n (o =
parte de
ella) contenida en este mensaje. Por favor notif=EDquenos respondiendo =
al
remitente, borre el mensaje original y borre las copias (impresas o =
en cualquier medio magn=E9tico) que pueda haber realizado del mismo.=20

Todas las opiniones contenidas en este mail son propias del autor del
mensaje y no necesariamente coinciden con las de Telef=F3nica =
Comunicaciones
Personales S.A. o alguna empresa asociada.=20

Los mensajes electr=F3nicos pueden ser alterados, motivo por el cual
Telef=F3nica Comunicaciones Personales S.A. no aceptar=E1 ninguna =
obligaci=F3n
cualquiera sea el resultante de este mensaje.=20

Muchas Gracias.

------_=_NextPart_001_01C310E7.D8582150
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Diso-8859-1">
<META NAME=3D"Generator" CONTENT=3D"MS Exchange Server version =
5.5.2654.45">
<TITLE>RE: convert integer to binary</TITLE>
<BODY>

<P><FONT SIZE=3D2>One way can be this:</FONT>
</P>

<P><FONT SIZE=3D2>&gt;&gt;&gt; def IntToBin(num):</FONT>
<BR><FONT SIZE=3D2>...&nbsp;&nbsp;&nbsp;&nbsp; bin =3D =
&quot;&quot;</FONT>
<BR><FONT SIZE=3D2>...&nbsp;&nbsp;&nbsp;&nbsp; while num:</FONT>
<BR><FONT =
SIZE=3D2>...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp; bin +=3D str(num%2)</FONT>
<BR><FONT =
SIZE=3D2>...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp; num /=3D 2</FONT>
<BR><FONT SIZE=3D2>...&nbsp;&nbsp;&nbsp;&nbsp; return bin</FONT>
<BR><FONT SIZE=3D2>... </FONT>
<BR><FONT SIZE=3D2>&gt;&gt;&gt; IntToBin(9)</FONT>
<BR><FONT SIZE=3D2>'1001'</FONT>
<BR><FONT SIZE=3D2>&gt;&gt;&gt; IntToBin(127)</FONT>
<BR><FONT SIZE=3D2>'1111111'</FONT>
</P>

<P><FONT SIZE=3D2>I just made it. Can it be optimized? </FONT>
</P>

<P><FONT SIZE=3D2>One way to optimize could be instead of add strings, =
just append in list, and the return a =
&quot;&quot;.join(str(list))</FONT>
</P>

<P><FONT SIZE=3D2>How can I easily test the speed of this?</FONT>
</P>
<BR>

<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <FONT =
SIZE=3D2>Facundo</FONT>
</P>
<BR>
<BR>

<P><FONT SIZE=3D2>#- -----Mensaje original-----</FONT>
<BR><FONT SIZE=3D2>#- De: ekranawetter [at] utanet [<A =
HREF=3D"mailto:ekranawetter [at] utanet">mailto:ekranawetter [at] utanet</A>=
]</FONT>
<BR><FONT SIZE=3D2>#- Enviado el: Viernes 2 de Mayo de 2003 4:31 =
PM</FONT>
<BR><FONT SIZE=3D2>#- Para: python-list [at] python</FONT>
<BR><FONT SIZE=3D2>#- Asunto: convert integer to binary</FONT>
<BR><FONT SIZE=3D2>#- </FONT>
<BR><FONT SIZE=3D2>#- </FONT>
<BR><FONT SIZE=3D2>#- Hi all,</FONT>
<BR><FONT SIZE=3D2>#- </FONT>
<BR><FONT SIZE=3D2>#- I couldn't find any function in Python to convert =
integers to binary</FONT>
<BR><FONT SIZE=3D2>#- and vice versa, for example:</FONT>
<BR><FONT SIZE=3D2>#- </FONT>
<BR><FONT SIZE=3D2>#- integer 16 =3D bin 10000, or </FONT>
<BR><FONT SIZE=3D2>#- integer 15 =3D bin&nbsp; 1111</FONT>
<BR><FONT SIZE=3D2>#- bin 11 =3D integer 3</FONT>
<BR><FONT SIZE=3D2>#- </FONT>
and</FONT>
<BR><FONT SIZE=3D2>#- ekranawetter [at] bmw</FONT>
<BR><FONT SIZE=3D2>#- </FONT>
<BR><FONT SIZE=3D2>#- Thanks</FONT>
<BR><FONT SIZE=3D2>#- -- </FONT>
<BR><FONT SIZE=3D2>#- <A =
HREF=3D"http://mail.python.org/mailman/listinfo/python-list" =
TARGET=3D"_blank">http://mail.python.org/mailman/listinfo/python-list</A=
></FONT>
<BR><FONT SIZE=3D2>#- </FONT>
</P>
<BR>
<BR>
<BR>
<BR>

<P><B><FONT SIZE=3D2>. . . . . . . . . . . . . . . . . . . . . . . . . =
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . =
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . =
.</FONT></B></P>

</P>

<P><B><FONT SIZE=3D2>La informaci=F3n contenida en este mensaje y =
cualquier archivo anexo al mismo, son para uso exclusivo del =
destinatario y pueden contener informaci=F3n confidencial o =
propietaria, cuya divulgaci=F3n es sancionada por la ley. =
</FONT></B></P>

<P><B><FONT SIZE=3D2>Si Ud. No es uno de los destinatarios consignados =
o la persona responsable de hacer llegar este mensaje a los =
distribuir o retener informaci=F3n (o parte de ella) contenida en este =
mensaje. Por favor notif=EDquenos respondiendo al remitente, borre el =
mensaje original y borre las copias (impresas o grabadas en cualquier =
medio magn=E9tico) que pueda haber realizado del mismo. </FONT></B></P>

<P><B><FONT SIZE=3D2>Todas las opiniones contenidas en este mail son =
propias del autor del mensaje y no necesariamente coinciden con las de =
Telef=F3nica Comunicaciones Personales S.A. o alguna empresa asociada. =
</FONT></B></P>

<P><B><FONT SIZE=3D2>Los mensajes electr=F3nicos pueden ser alterados, =
motivo por el cual Telef=F3nica Comunicaciones Personales S.A. no =
aceptar=E1 ninguna obligaci=F3n cualquiera sea el resultante de este =
mensaje. </FONT></B></P>

<P><B><FONT SIZE=3D2>Muchas Gracias.</FONT></B>
</P>

</BODY>
</HTML>
------_=_NextPart_001_01C310E7.D8582150--

jolderdissen at ixiacom

May 2, 2003, 2:05 PM

Post #4 of 9 (3200 views)
 convert integer to binary [In reply to]
>I couldn't find any function in Python to convert integers to binary
>and vice versa, for example:

Try int ("1111", 2) to go from binary to integer. For the reverse
direction, you'll probably have to implement a couple of lines of
actual code. :-)

Jan

http

May 2, 2003, 3:42 PM

Post #5 of 9 (3192 views)
 convert integer to binary [In reply to]
ekranawetter [at] utanet (ekranawetter-piber) writes:

> Hi all,
>
> I couldn't find any function in Python to convert integers to binary
> and vice versa, for example:
>
> integer 16 = bin 10000, or
> integer 15 = bin 1111
> bin 11 = integer 3

Note this doesn't bother stripping leading zeros from the result:

def i2b(n):
hdigits = ('0000','0001','0010','0011','0100','0101','0110','0111',
'1000','1001','1010','1011','1100','1101','1110','1111')

a = [hdigits[int(d,16)] for d in hex(n)[2:]]
return ''.join(a)

danb_83 at yahoo

May 2, 2003, 8:49 PM

Post #6 of 9 (3196 views)
 convert integer to binary [In reply to]
Jan Olderdissen <jolderdissen [at] ixiacom> wrote in message news:<u8n5bvo6ks4lg757ujptg6i5v2v0gpsk08 [at] 4ax>...
> >I couldn't find any function in Python to convert integers to binary
> >and vice versa, for example:
>
> Try int ("1111", 2) to go from binary to integer. For the reverse
> direction, you'll probably have to implement a couple of lines of
> actual code. :-)

I've implemented such a function in only one line before, but here's
the readable version, plus 3 related functions.

# ------------ baseconv.py ------------

from __future__ import division
import string, math

digits = string.digits + string.uppercase

"the integer represented by the string s in the given base"
try:
except OverflowError:

"the float represented by the string s in the given base"
if s[0] == '-':
decimalPointIndex = s.find('.')
if decimalPointIndex < 0:
fPart = s[decimalPointIndex+1:]
if fPart:
else:
fPart = 0
return iPart + fPart

"the string representing the integer num in the given base"
if num == 0:
return '0'
isNegative = num < 0
if isNegative:
num = -num
d = []
while num > 0:
d.append(digits[lastDigit])
if isNegative:
d.append('-')
d.reverse()
return ''.join(d)

"the string representing the float num in the given base"
if num < 0:
significantDigits = int(math.ceil(52 * math.log(2) /
leftDigits = int(math.log(num) / math.log(radix) + 1)
decimalPlaces = max(significantDigits - leftDigits, 0)
scaledNum = long(num * radix ** decimalPlaces + 0.5)
iPart, fPart = divmod(scaledNum, radix ** decimalPlaces)
s = "%s.%s" % (iPart, fPart)
lastDigitPosition = len(s) - 1
while s[lastDigitPosition] == digits[0]:
lastDigitPosition -= 1
return s[:lastDigitPosition+1]

egosum at xs4all

May 3, 2003, 2:58 AM

Post #7 of 9 (3200 views)
 convert integer to binary [In reply to]
Almost there?
>>> print IntToBin(0)

>>> print IntToBin(4)
001
>>> print IntToBin(6)
011

;-)

Regards,
Henk Burgstra

bokr at oz

May 3, 2003, 1:20 PM

Post #8 of 9 (3198 views)
 convert integer to binary [In reply to]
On 02 May 2003 15:42:21 -0700, Paul Rubin <http://phr.cx [at] NOSPAM> wrote:

>ekranawetter [at] utanet (ekranawetter-piber) writes:
>
>> Hi all,
>>
>> I couldn't find any function in Python to convert integers to binary
>> and vice versa, for example:
>>
>> integer 16 = bin 10000, or
>> integer 15 = bin 1111
>> bin 11 = integer 3
>
>Note this doesn't bother stripping leading zeros from the result:
>
>def i2b(n):
> hdigits = ('0000','0001','0010','0011','0100','0101','0110','0111',
> '1000','1001','1010','1011','1100','1101','1110','1111')
>
> a = [hdigits[int(d,16)] for d in hex(n)[2:]]
> return ''.join(a)

Stripping leading zeroes is easy enough
return ''.join(a).lstrip('0')

... digs in dustbin... (first bit is explicit 2's complement sign bit here)

>>> def binstr(n, maxbits=None):
... absn = abs(n)
... s=[.chr(((n>>b)&1)+48) for b in xrange(maxbits or len(hex(n))*4)
... if maxbits or not b or absn>>(b-1)]
... s.reverse()
... return ''.join(s)
...
>>> binstr(15)
'01111'
>>> binstr(16)
'010000'
>>> binstr(-15)
'10001'
>>> binstr(-16)
'110000'
>>> binstr(-16,32)
'11111111111111111111111111110000'
>>> for i in range(-9,10): print binstr(i),
...
10111 11000 1001 1010 1011 1100 101 110 11 0 01 010 011 0100 0101 0110 0111 01000 01001

BTW, len(hex(n))*4 is just to get a sufficient count, not an exact one, so the 'L'
on the end of a long doesn't hurt except a few extra loops in the list comp that don't

BTW2, anybody for binary literals of the form sbxxxx, where s is the sign bit as above
and xxxx is the rest? Similar to a proposed hex format of 0xnnnn and 1xnnn to indicate
what sign bit to extend above the bottom bits. Works nicely for unified ints and longs.

Regards,
Bengt Richter

scott.daniels at acm

May 9, 2003, 9:11 AM

Post #9 of 9 (3224 views)
 convert integer to binary [In reply to]
As long as we are fiddling:

Paul Rubin wrote:
> ekranawetter [at] utanet (ekranawetter-piber) writes:
>>I couldn't find any function in Python to convert integers to binary
> Note this doesn't bother stripping leading zeros from the result:
> def i2b(n):
> hdigits = ('0000','0001','0010','0011','0100','0101','0110','0111',
> '1000','1001','1010','1011','1100','1101','1110','1111')
>
> a = [hdigits[int(d,16)] for d in hex(n)[2:]]
> return ''.join(a)

def i2b(n):
"""Convert an integer to its binary text representation"""
if n <= 0:
if n < 0:
return '-' + i2b(-n)
return '0'
octaldigits = '000','001','010','011','100','101','110','111'
octaltext = oct(n).rstrip('L')
a = [octaldigits[int(digit)] for digit in octaltext]
return ''.join(a).lstrip('0')

if __name__ == '__main__':
assert map(i2b, [0,1,2,4,8, 16, 32, 21L, 3L, -2, -5L]) == (
'0 1 10 100 1000 10000 100000 10101 11 -10 -101'.split())

-Scott David Daniels
Scott.Daniels [at] Acm