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