How to convert a number to binary?

Paul McGuire ptmcg at austin.rr.com
Thu May 17 19:59:04 EDT 2007


On May 17, 6:45 pm, Lyosha <lyos... at gmail.com> wrote:
> 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)
>

Howzis?

"".join(map(str,[ int(bool(n & 2**i)) for i in range(20) if n>2**i ]
[::-1]))

Uses:
- integer & to test for bit high or low, returns 2**i
- bool(int) to evaluate boolean value of integers - zero -> False,
nonzero -> True
- int(bool) to convert True->1 and False->0

-- Paul




More information about the Python-list mailing list