Base 2 to long integers and back

Tim CHURCHES TCHUR at doh.health.nsw.gov.au
Wed Mar 21 01:43:43 EST 2001


Brian,

Thanks. I just discovered that the string.atol() function (or the long() built-in in 2.x) takes an optional radix argument, thusly:

>>> a = '0000101010100000111010101001010000111110100101010100101010010100101010100101010100000111110101010101000101001001001010'>>> print string.atol(a,2)13796684847850186040196945077883466L
but there is no built-in or library function which does the reverse, it would seem. However your code does the trick nicely and quite quickly, although a small C extension to do the same would be nifty. Now where did I put my copy of "Teach Yourself C in 23 Minutes or More"?

Cheers,

Tim C

>>> Brian Quinlan <brian at sweetapp.com> 21/03/2001 17:19:11 >>>
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