[Tutor] to/from binary to/from integer (i.e.'01010101' = 85)

Terry Carroll carroll at tjc.com
Fri Jan 2 12:03:45 EST 2004


On Fri, 2 Jan 2004, Todd G. Gardner wrote:

> I was wondering if anyone happens to know how to convert to/from binary
> to/from integer (i.e.'01010101' = 85)

Here's a quick and dirty, with no error checking:

def binstring2dec(str):
    result = 0
    for i in range(0,len(str)):
        result = (result*2)+(str[i]=="1")
    return result

It just loops through the string, multiplying an accumulated result by two 
each time, and incrementing it when a 1 is detected.

As I said, it does no error checking; it assumes that each character in
the string is either a "1" or a "0", so a bug is that if you send it a
noncompliant string, any non-1 character will be treated as a zero:

>>> binstring2dec("01010101")
85
>>> binstring2dec("21212121")
85
>>> binstring2dec("x1x1x1x1")
85

Come to think of it, here's better one, that's a little cleaner (it 
doesn't depend on True == 1), and will choke on bad data:

def binstring2dec(str):
    result = 0
    lookup = {'0':0, '1':1}
    for i in range(0,len(str)):
        result = (result*2)+lookup[str[i]]
    return result

>>> binstring2dec("01010101")
85
>>> binstring2dec("21212121")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "bintest.py", line 11, in binstring2dec
    result = (result*2)+lookup[str[i]]
KeyError: '2'

-- 
Terry Carroll
Santa Clara, CA
carroll at tjc.com 




More information about the Tutor mailing list