These are the operators of bit shifting. That is, operators who change the bit representation value by "pushing" it to one side.
<<
pushes to the left and >>
pushes right.
The number 5, for example, has representation 000...00000101
.
5 << 2
moves the bits two positions (filling with zeros the new places), so we have 000...00010100
, that is, 20.
5 >> 2
moves the bits two positions to the other side, so we have 000...00000001
, that is, 1.
In practice, the operator x << n
multiplies x
by 2n (for example, x << 1
multiplies by 2) and the operator x >> n
divided by 2n (for example, x >> 1
divide by 2, truncating the results).
All these operators convert to 32-bit integers the values of the operands before applying the operations. If the right operand is greater than 32, only the 5 significant bits of that operand are used (therefore, x >> 2
is equal to x >> 66
)
To understand how these operators behave with negative numbers, it is important to understand how negative numbers are represented in memory.
The format used by these operators assumes a complement of two.
In this model, reversing the signal of a number is equivalent to reversing all bits and then adding 1.
Example:
Número 2: 00000...000010
Invertendo todos os bits: 11111...111101
Somando 1: 11111...111110
Hence the representation of the number -2
is: 111111...111110
. A number is positive if the most significant bit (the leftmost bit) is 0, and negative if the most significant bit is 1.
When applying -2 << 2
we’ve come to have 11111...111000
. What is this number?
Número X: 11111...111000
Invertendo todos os bits: 00000...000111
Somando 1: 00000...001000 (que significa 8)
Soon -2 << 2 === -8
. Again we see that the effect is to multiply by 2n.
The difference between >>
and >>>
is that the >>
fills the bits entered on the left with the value of the most significant bit of the left operand, while >>>
fills the entered bits with 0.
-4 >> 1
gives -2
, but -4 >>> 1
gives:
Número 4: 0000...000100
Número -4: 1111...111100
Resultado: 0111...111110 (ou seja, 2^31 - 2)
We can thus say that the >>
maintains the signal while >>> N
always gives a positive number (provided that N > 0).
Documentation (in English)
+1 much more complete than my reply, thank you.
– Gabriel Gartz