Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 3<<1 == 6 in python? [duplicate]

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

anyone can explain me that operator << or >>

like image 632
elgianka Avatar asked Oct 12 '10 18:10

elgianka


People also ask

What is the meaning of ::- 1 in Python?

[::-1] means: Start at the end (the minus does that for you), end when nothing's left and walk backwards by 1.

How does Left Shift work Python?

Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.

How does Left Shift and Right Shift Work?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.


4 Answers

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
like image 112
Mark Byers Avatar answered Oct 30 '22 04:10

Mark Byers


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)

like image 25
Gabi Purcaru Avatar answered Oct 30 '22 03:10

Gabi Purcaru


It's a shift operator.

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

like image 31
Julio Santos Avatar answered Oct 30 '22 04:10

Julio Santos


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

like image 4
Reed Copsey Avatar answered Oct 30 '22 04:10

Reed Copsey