binary to decimal conversion

Greg Jorgensen gregj at pobox.com
Wed Mar 22 01:48:15 EST 2000


what's wrong with

    i = string.atoi(s, 2)

?
if you want to roll your own for some reason, this works:

def atobin(str):
    v = 0L
    for c in s:
        v = v << 1
        if c == '1': v = v + 1
    return v


If the result is negative you overflowed.

You can find out how many binary digits an integer will use with this
function:

def binarydigits(n):
    if n = 0:
        return 1
    else:
        return 1 + int(math.log(abs(n)) / math.log(2))

(negative numbers are usually represented with a sign bit, but that's a
detail I won't worry about)

On my system (Windows 2000), binarydigits(sys.maxint) returns 31.

Greg Jorgensen
gregj at pobox.com






More information about the Python-list mailing list