From: alex at somewhere.round.here (Alex)
Date: 16 Apr 1999 10:01:20 -0400
Subject: binary
References: <37171BD5.87CFA015@efes.net.tr>
Message-ID: <etdogko3brj.fsf@m2-225-11.mit.edu>
Content-Length: 1784
X-UID: 864                                                  

There were a whole lot of solutions to this posted here a little while
ago.  I'm not sure if I'm duplicating an earlier method.  Anyway, this
might be a bit slow, but it seems to work for any base:

**************************************************************
import math

chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def base_repr (number, base = 2, padding = 0):
    if number < base: \
       return (padding - 1) * chars [0] + chars [int (number)]
    max_exponent = int (math.log (number)/math.log (base))
    max_power = long (base) ** max_exponent
    lead_digit = int (number/max_power)
    return chars [lead_digit] + \
           base_repr (number - max_power * lead_digit, base, \
                      max (padding - 1, max_exponent))

print map (base_repr, 17 * [17], range (2, 19))
**************************************************************

The result is

['10001', '122', '101', '32', '25', '23', '21', '18', '17', \
'16', '15', '14', '13', '12', '11', '10', 'H']

If you just want binary, there is a slightly slicker way:

**************************************************************
import math, operator, string

def binary_repr (number, max_length = 32):
    # This will only work reliably for relatively small numbers.
    # Increase the value of max_length if you think you're going
    # to use long integers
    assert number < 2L << max_length
    shifts = map (operator.rshift, max_length * [number], \
                  range (max_length - 1, -1, -1))
    digits = map (operator.mod, shifts, max_length * [2])
    if not digits.count (1): return 0
    digits = digits [digits.index (1):]
    return string.join (map (repr, digits), '')
    
print binary_repr (17)
**************************************************************

See you.
Alex.




