Interesting problem comparing strings with integer values...

Andrew McGregor andrew at indranet.co.nz
Thu Jan 16 04:28:35 CET 2003


There is one such in the IPy IP Address manipulation module, as follows:

_BitTable = {'0': '0000', '1': '0001', '2': '0010', '3': '0011',
            '4': '0100', '5': '0101', '6': '0110', '7': '0111',
            '8': '1000', '9': '1001', 'a': '1010', 'b': '1011',
            'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'}

def _intToBin(val):
    """Return the binary representation of an integer as string."""

    if val < 0:
        raise ValueError, "Only positive Values allowed"
    s = hex(val).lower()
    ret = ''
    if s[-1] == 'l':
        s = s[:-1]
    for x in s[2:]:
        if __debug__:
            if not _BitTable.has_key(x):
                raise AssertionError, "hex() returned strange result"
        ret += _BitTable[x]
    # remove leading zeros
    while ret[0] == '0' and len(ret) > 1:
        ret = ret[1:]
    return ret


--On Wednesday, January 15, 2003 18:29:54 -0600 Chris Spencer 
<clspence at one.net> wrote:

> However, I've not been able to find an equivalent to hex() or oct() that
> would turn integers into binary string representation.  If there IS such
> a beastie, please let me know.
>
> Chris.






More information about the Python-list mailing list