Equivalent of Javascript Bitwise Operators

Bengt Richter bokr at oz.net
Wed Oct 27 20:00:32 EDT 2004


On 27 Oct 2004 04:04:36 -0700, fuzzyman at gmail.com (Michael Foord) wrote:

>Please pardon my ignorance on this one - but I'm not certain how the
>sign bt is treated in python bitwise operators. I've trying to convert
>a javascript DES encryption routine into python.
>
>Javascritp has >>> and >>. >>> is a zero fill bit shift whereas >> is
>a sign propagating bit shift. My understanding is that the python >>
>is equivalent to the javascript >> - but python has no equivalent to
>>>>.
>
>Would a >>> 3 in javascript be equivalent to abs(a) >> 3 in python
>(make sure the sign bit is set to zero first) ?
>
No. Python has the sign bit virtually extended infinitely to the left, so
you'll never see the zeroes ;-)

IOW, python (no longer) make the assumption that bit 31 (or 63 on 64 bit platforms??!!)
is a sign bit in its integers. Unification of int and long is behind that.

If you want to shift in zeroes from above 32 bits of a possibly negative number,
mask it down to 32 bits, don't use abs. I.e, use int((a&0xffffffffL) >> 3)

(A 32-bit positive number with zeroes in the sign bits has to be a long unless
you have a 32-bit machine. The unification is trying to get away from that platform
dependency from version 2.4 on (I have 2.3). Then hex literals will all be positive
numbers. But I guess there will still be an int/long representation duality, so if
you want to make the above int again, after the & with a long constant, you have to
do the int(result). I'm not sure what type(a&0xffffffff) >> 3) will be in 2.4, but
I suspect long. I guess I should install the new beta.

>In actual fact I'm now using DES3 from Pycrypto - but I'm still
>interested in the answer to the question. In case anyone is interested
>I've done some work with some Javascript encryption and python
>equivalents. Thsi allows you to build client side encryption into
>webpages - e.g. for secure logins. It all works - very nice.
>

Regards,
Bengt Richter



More information about the Python-list mailing list