Integer to "binary string"?
darrell
dgallion1 at yahoo.com
Sun Dec 15 15:13:00 EST 2002
i=5
s = ''
while i:
print 'S top: %4s I top: %d'%(s,i)
s = (i & 1 and '1' or '0') + s # (i&1) is bitwise AND, so 5 & 1 is 1
# If the result of i & 1 is 1 then add '1' to s
i >>= 1 # right shift 1 and put the result back into 'i'
print 'S bot: %4s I bot: %d'%(s,i)
print s
---Output
S top: I top: 5
S bot: 1 I bot: 2
S top: 1 I top: 2
S bot: 01 I bot: 1
S top: 01 I top: 1
S bot: 101 I bot: 0
101
--Darrell
Gustaf Liljegren wrote:
> 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