On May 17, 2007, at 6:33 PM, Lyosha wrote:

> Converting binary to base 10 is easy:
>>>> int('11111111', 2)
> 255
>
> Converting base 10 number to hex or octal is easy:
>>>> oct(100)
> '0144'
>>>> hex(100)
> '0x64'
>
> Is there an *easy* way to convert a number to binary?


def to_base(number, base):
        'converts base 10 integer to another base'

        number = int(number)
        base = int(base)        
        if base < 2 or base > 36:
                raise ValueError, "Base must be between 2 and 36"       
        if not number:
                return 0
                
        symbols = string.digits + string.lowercase[:26] 
        answer = []
        while number:
                number, remainder = divmod(number, base)
                answer.append(symbols[remainder])       
        return ''.join(reversed(answer))

Hope this helps,
Michael

---
"I would rather use Java than Perl. And I'd rather be eaten by a  
crocodile than use Java." — Trouser


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to