Base 2 to long integers and back

Brian Quinlan brian at sweetapp.com
Wed Mar 21 01:19:11 EST 2001


I can't think of a library function that does this, but it should be pretty
easy to do it yourself.

String to int:

>>> test = '10110'
>>> val = 0L
>>> for i in test:
...     val <<= 1
...     if i == '1':
...             val += 1
>>> val
22

OR, for the anal and efficiency oriented:

>>> test = '10110'
>>> val = 0L
>>> for i in test:
...     val = ( val << 1 ) + ( ord( i ) & 1 )
>>> val
22

Int to string:

>>> out = ''
>>> val = 100
>>> while val:
...     out = str( val & 1 ) + out
...     val >>=1
>>> out
'1100100'

-----Original Message-----
From: python-list-admin at python.org
[mailto:python-list-admin at python.org]On Behalf Of Tim CHURCHES
Sent: Tuesday, March 20, 2001 7:23 PM
To: python-list at python.org
Subject: Base 2 to long integers and back


Can anyone suggest a fast method of converting base2 strings (e.g.
'0000101110') to Python long integers, and back? I couldn't locate any
functions in the standard library to do this, but no doubt I am overlooking
something obvious.

Cheers,

Tim Churches
Sydney, Australia



--
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list