views:

474

answers:

4

Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?

anyone can explain me that operator << or >>

+13  A: 

3, in binary, is 11 and shifted to left one bit is 110, or 6 in decimal.

Think of a << b as a * (2 ** b)

>> is for right-shifting. Think of a >> b as a // (2 ** b)

Gabi Purcaru
Python isn't BASIC, so `a<<b` would be equivalent to `a*2**b` or `a*(2**b)` (and likewise for `>>`.
martineau
-1 Think of `a << b` as `a * 2 ** b`
John Machin
@martineau of course, I was trying to write it in a more readable format. But you are right. Modified.
Gabi Purcaru
Might be better expressed as `a*pow(2,b)`.
martineau
@John Machin - Thanks for including the use of `//`. I think a lot of people are going to be surprised that `/` always means floating point division in Python3.
Omnifarious
+3  A: 

It's a shift operator.

http://docs.python.org/reference/expressions.html#shifting-operations

Júlio Santos
+3  A: 

It's a bit shift, using a shifting operation.

Say you have a number, and looking at the lowest bits, you have 3:

0 0 1 1

If you shift it, you'll get 6, or:

0 1 1 0

Reed Copsey
+25  A: 

The << and >> operators are bitshift operators. x << 1 shifts all the bits in x up to the next most significant bit, effectively multiplying by 2. More generally, x << n shifts the bits up n positions. To understand how this operation works it is easiest to look at the binary representation:

3         0000011 =  3
3 << 1    0000110 =  6
3 << 2    0001100 = 12
3 << 3    0011000 = 24

Similarly the >> operator shifts the bits down:

58        0111010 = 58
58 >> 1   0011101 = 29
58 >> 2   0001110 = 14
58 >> 3   0000111 = 7
58 >> 4   0000011 = 3
58 >> 5   0000001 = 1
58 >> 6   0000000 = 0
Mark Byers