convert integer to binary

Fernando Perez fperez528 at yahoo.com
Fri May 2 16:13:35 EDT 2003


ekranawetter-piber wrote:

> Hi all,
> 
> I couldn't find any function in Python to convert integers to binary
> and vice versa, for example:
> 
> integer 16 = bin 10000, or
> integer 15 = bin  1111
> bin 11 = integer 3

These are pulled from by bitbucket.  I don't claim credit for them, as it's
quite possible that they are reworks of code I found on the net:

def base_repr (number, base = 2, padding = 0):
    """Return the representation of a number in any given base."""
    chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    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))

def binary_repr (number, max_length = 64):
    """Return the binary representation of the input number as a string.

    This is more efficient than using base_repr with base 2.

    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 ''.join (map (repr, digits)).replace('L','')

def bin(i):
    """Return the binary representation of the input number as a string.

    Efficient, but returns leading zeros."""

    l = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
         '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
    s = ''.join(map(lambda x: l[int(x, 16)], hex(i)[2:]))
    if s[0] == '1' and i > 0:
        s = '0000' + s
    return s

> 
> please help and send an email to this adress and
> ekranawetter at bmw.co.at

Cheers,

f.




More information about the Python-list mailing list