Integer to "binary string"?
Alfred Morgan
amorgan at netlojix.com
Mon Dec 16 18:27:53 EST 2002
I decided to write a version 2 of my bin function. Since version 1
couldn't handle negative numbers I added an assertion otherwise it would
get stuck in an infinite loop. I also changed the way s added a '0' or
'1' since Dan didn't like my "short-circuiting" and/or method. I like
it this way much better anyway because it's more petite.
def bin(i):
assert i >= 0, "Can't be used for negative numbers."
s = ''
while i:
s = '01'[i & 1] + s
i >>= 1
return s or '0'
-alfred
Dan Bishop wrote:
> 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