Integer to "binary string"?
Dan Bishop
danb_83 at yahoo.com
Sun Dec 15 18:16:48 EST 2002
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:
A binary to integer conversion can be done with int(bitString, 2).
There's a standard function to convert the other way, but right now I
don't remember what it's called.
> 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?
The code is (imho) obfuscated, so I'll rewrite it to increase clarity
by replacing the and's and or's with if's and else's, using the
short-circuiting property of "and" and "or".
def bin(i):
s = ''
while i:
if i & 1:
s = '1' + s
else:
s = '0' + s
i >>= 1
if s:
return s
else:
return '0'
> if i & 1:
& is a bitwise AND operator, and the bitmask 1 corresponds to the last
bit of the number. If this bit is nonzero (i.e., 1), a '1' is added
to the s; otherwise, a '0' is added. (Why is it added to the front
instead of the end? We'll see later.)
> i >>= 1
Right shift by one bit; throw away the last bit of of i.
The recursive definition of an int-to-binary string conversion is
(all but the last bit of i) + str(last bit of i)
= bin(i >> 1) + str(i & 1)
This iterative version calculates these terms in reverse order, which
is why the string s is built in reverse order.
> return s or '0'
If s is true (i.e., len(s) > 0), then s is returned. Otherwise, '0'
is returned.
More information about the Python-list
mailing list