binary

Alex alex at somewhere.round.here
Fri Apr 16 10:01:20 EDT 1999


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.




More information about the Python-list mailing list