How to convert a number to binary?

Stargaming stargaming at gmail.com
Fri May 18 02:04:23 EDT 2007


Lyosha schrieb:
> On May 17, 4:40 pm, Michael Bentley <mich... at jedimindworks.com> wrote:
> 
>>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
> 
> 
> That's way too complicated...  Is there any way to convert it to a one-
> liner so that I can remember it?  Mine is quite ugly:
>     "".join(str((n/base**i) % base) for i in range(20) if n>=base**i)
> [::-1].zfill(1)
> 

Wrote this a few moons ago::

   dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''

Regards,
Stargaming



More information about the Python-list mailing list