[Tutor] Enhanced base 10 to base 2 converter

Kirby Urner urnerk@qwest.net
Fri, 21 Jun 2002 09:46:32 -0400


Here's a somewhat improved version of the convert-to-base2 function.  
It'll pad to the left with the sign bit (0 for positive, 1 for 
negative) up to the nearest word boundary, where wordsize is whatever.  
This way, if it's a long integer, you don't hit overflow conditions 
by exceeding the word size -- just keep eating words as needed.

Usage:




=============

def base2(n,wordsize=16):
    """
    Convert an integer to base 2 string representation using 
    as many words as needed (could be enhanced to flag overflow
    for ints of fixed maximum size, with this kind of indefinite 
    expansion for long ints only)

    Note: negative numbers are in two's complement representation

    """
    if (type(n) != type(1) and type(n) != type(1L)): 
       raise ValueError,"Needs int or long int"

    outstr = ''
    j=abs(n)

    fill=0  # fill is sign bit (0=pos, 1=neg)
    if n<0: fill=1

    while 1:
       if n&1: outstr = '%s%s' % ('1',outstr)
       else:   outstr = '%s%s' % ('0',outstr)
       n>>=1  # n is actual number to be converted
       j>>=1  # j is positive moving to 0 as shifted
       if j==0: break

    # positive number cannot have 1 in first position
    # note: n reached 0 only if it was positive to begin with
    if n==0 and outstr[0]=='1': outstr = "%s%s" % ('0',outstr)

    # pad left w/ sign bits from nearest word boundary
    while len(outstr) % wordsize > 0:  
       outstr = '%s%s' % (fill,outstr)

    return outstr