Integer to "binary string"?

Levente Sandor sandorlevi at yahoo.com
Sun Dec 15 21:32:12 EST 2002


Chapter 5.10 in the Python Reference Manual -
http://python.org/doc/current/ref/Booleans.html explains how the
boolean expressions are evaluated:
"The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is
returned.

The expression x or y first evaluates x; if x is true, its value is
returned; otherwise, y is evaluated and the resulting value is
returned."

----
Levi

Gustaf Liljegren <gustafl at algonet.se> wrote in message news:<Xns92E5D08902B0Fgustafl at 195.100.94.182>...
> I'm writing a short program to help me understand certain concepts of the 
> character encoding UTF-16. The script should be able to encode integers to 
> strings of ones and zeros, to illustrate what happens during serialization.
> 
> I was hunting for a function to convert integers to these strings and vice 
> versa, but found none. Then I hunted on Google and found:
> 
> def bin(i):
>      s = ''
>      while i:
>          s = (i & 1 and '1' or '0') + s
>          i >>= 1
>      return s or '0'
> 
> This works, but I don't understand it. Can anyone explain what happens on 
> the three last rows? Also, can you show how to write a similar function for 
> decoding?
> 
> Gustaf



More information about the Python-list mailing list