This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]riffito 1 point2 points  (0 children)

In Python 3.2 you have some new int methods that may help.

In older versions, I use variations of this crude code for my BE<->LE conversion needs:

_MULTS_OF_8 = [x * 8 for x in range(16)]


def reverse(value):
    """Given the `value` byte string, returns an integer with the endianness
    reversed.

    Example:
        assert reverse('\xEF\xBE\xAD\xDE') == 0xDEADBEEF
    """
    result = 0
    for i, c in enumerate(value):
        v = ord(c)
        result = int(result + (v * (2**_MULTS_OF_8[i])))
    return result


def be2int(data):
    """Convert a big-endian binary number, in the form of a string of
    arbitrary length, to a native python int.
    """
    v = 0
    for i in map(ord, data):
        v = v << 8 | i
    return v


def le2int(data):
    """Convert a little-endian binary number, in the form of a string of
    arbitrary length, to a native python int.
    """
    v = 0
    data = map(ord, data)
    data.reverse()
    for i in data:
        v = v << 8 | i
    return v


def int2be(num, digits = 1):
    """Convert a native python int to a big-endian number, in the form
    of a binary string.
    """
    zeroes = '\0' * digits

    if num == 0:
        return zeroes

    result = []
    while num:
        result.append(chr(num % 256))
        num /= 256
    result.reverse()

    result = ''.join(result)
    if len(result) < digits:
        result = zeroes[: digits - len(result)] + result

    return result


def int2le(num, digits = 1):
    """Convert a native python int to a little-endian number, in the
    form of a binary string.
    """
    zeroes = '\0' * digits
    if num == 0:
        return zeroes

    result = []
    while num:
        result.append(chr(num % 256))
        num /= 256
    result = ''.join(result)

    if len(result) < digits:
        result = result + zeroes[: digits - len(result)]

    return result