Integer to "binary string"?

Gustaf Liljegren gustafl at algonet.se
Sun Dec 15 14:31:52 EST 2002


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