Seite 1 von 1

int2str mit Basis von 2 bis 36

Verfasst: Montag 28. November 2005, 00:32
von BlackJack
Gibt's bestimmt schon tausend mal, aber ich brauchte eine Umwandlung von ganzen Zahlen in eine Zeichenkette zur Basis 32. Habe dann gleich was generisches gestrickt:

Code: Alles auswählen

#!/usr/bin/env python
"""The built-in `int()` can convert numbers in string format in bases from 2 to
36 into integers but there is no reverse function except the string formating
for bases 8, 10, and 16.

:var DIGITS: a string containing all characters considered digits up to base 36.
:var _string_formatting: a mapping of bases to string formating codes.
"""

__author__ = "Marc 'BlackJack' Rintsch"
__version__ = '0.1.0'
__date__ = '$Date: 2005-11-27 20:20:38 +0100 (Sun, 27 Nov 2005) $'
__revision__ = '$Rev: 797 $'

DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

_string_formatting = { 8: '%o', 10: '%d', 16: '%X' }

def int2str(value, base=10):
    """Convert an integer `value` into a string representation in given
    `base`.
    
    :raises ValueError: if `base` not in range [2, 36].
    """
    if not 2 <= base <= 36:
        raise ValueError('base must be >= 2 and <= 36')
    # 
    # Use string formating if possible because it is faster.
    # 
    if base in _string_formatting:
        return _string_formatting[base] % value
    # 
    # Save and remove the sign.
    # 
    if value < 0:
        sign = '-'
        value = -value
    else:
        sign = ''
    # 
    # Build a list with the digits in reversed order.
    # 
    result = list()
    while value:
        value, remainder = divmod(value, base)
        result.append(DIGITS[remainder])
    
    if not result:
        return '0'
    
    result.append(sign)
    
    return ''.join(reversed(result))


def convert(string, source_base, target_base):
    """Convert number given in `string` in `source_base` to the string
    representation in `target_base`.
    
    :raises ValueError: if `source_base` or `target_base` are not in
        range [2, 36] or `string` is not a valid literal number in
        `source_base`.
    """
    if source_base == target_base:
        return string
    else:
        return int2str(int(string, source_base), target_base)