bitwise shift?
Michael Hoffman
cam.ac.uk at mh391.invalid
Wed Apr 25 17:46:20 EDT 2007
Jean-Paul Calderone wrote:
> On Wed, 25 Apr 2007 22:54:12 +0200, desktop <fff at sss.com> wrote:
>> I have found a code example with this loop.
>>
>> for k in range(10, 25):
>> n = 1 << k;
>>
>>
>> I have never read Python before but is it correct that 1 get multiplied
>> with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift
>> left by k" which is the same as multiplying with k.
>
> No.
>
> http://python.org/doc/ref/shifting.html
"A right shift by n bits is defined as division by pow(2,n). A left
shift by n bits is defined as multiplication with pow(2,n); for plain
integers there is no overflow check so in that case the operation drops
bits and flips the sign if the result is not less than pow(2,31) in
absolute value. Negative shift counts raise a ValueError exception."
>>> sys.maxint << 2
8589934588L
>>> 2**31
2147483648L
It looks like the limitation has been removed. This might be a nice
optimization as well, as 1 << n is faster than 2**n for large enough n.
Might be rare, although I have a friend who has been doing this all day.
In Python.
--
Michael Hoffman
More information about the Python-list
mailing list