<<
and >>
are the shift operators. They shift the value of their first operand to the left/right with the number of bits specified by their second operand.
<<
Let's see how it works for 13 << 3
.
The binary representation of 13
is 1101
. In computer the value is stored on a fixed number of bits, depending on its type. Let's assume it is stored on 2 bytes in our program.
This is how 13
and 13 << 3
are represented on 2 bytes:
0000 0000 0000 1101 <--- 13
000 0000 0000 0110 1000 <--- 13 << 3
^^^ ^^^
| +----- 3 new bits
+----- these bits are lost
The bits of 13
are shifted 3 positions to the left. The leftmost 3 bits of the original value are lost. Three 0
bits are inserted on the right.
All in all, the value of a << b
is (a * 2^b) mod 256^n
where n
is the number of bytes used to represent the value of a
. A left shift works the same as a multiplication with a value that is a power of 2.
>>
The right shift (>>
) is similar. The bits are moved to the right, the rightmost bits are lost and new bits are inserted on the left. The bits inserted on the left side depend on the sign of the leftmost operand. If the value of the first operand is negative, the right shift inserts 1
to the left; otherwise it inserts 0
.
This behaviour produces a value that has the same sign as the first operand.
The right shift works as an integer division by a number that is a power of 2. The value of a >> b
is (a / 2^b)
.
Important!
Integer promotions are applied to both operands first. 13
in this example is handled as int
and on most nowadays architectures this means it is represented on 4 bytes, even if 1 byte is enough to store it.
The behaviour of both <<
and >>
is undefined if the number of bits to shift is negative or larger than the size in bits of the first operand after promotion.
Read more about the shift operators.