I came across the following calculation being assigned to a variable
(1103515245 * $num + 12345) % (1 << 31)
What do these <<
mean?
I came across the following calculation being assigned to a variable
(1103515245 * $num + 12345) % (1 << 31)
What do these <<
mean?
The <<
operator is not only in php, but in many other languages, it is a bit-to-bit operator .
What it does is to shift the value to the left of the operator n times, where n is the value to the right of the operator. (Move left obviously)
For example:
$a = 2 << 3;
// Em binário temos 2 = 0000 0010, deslocando ele 3x
// obtemos 0001 0000, que resulta em 16
echo $a; // 16
If you have more questions, you can consult the php manual: link
When the right-hand operator is 31, the shift-left operator is used for a very specific purpose: find out whether the left operator is even or odd.
If even, the result of par << 31
will be 0.
If it is odd, the result of impar << 31
will be -2147483648, the minimum value of integer types.
0
= 0 000 0000 0000 0000 0000 0000 0000 0000 em binario
= 0 000 0000 0000 0000 0000 0000 0000 0000 depois de shift left
= 0
1
= 0 000 0000 0000 0000 0000 0000 0000 0001 em binario
= 1 000 0000 0000 0000 0000 0000 0000 0000 depois de shift left
= -2147483648
2 =
= 0 000 0000 0000 0000 0000 0000 0000 0010 em binario
= 0 000 0000 0000 0000 0000 0000 0000 0000 depois de shift left
= 0
...
51 =
= 0 000 0000 0000 0000 0000 0000 0011 0011 em binario
= 1 000 0000 0000 0000 0000 0000 0000 0000 depois de shift left
= -2147483648
The logic is to shift to the left until all the digits disappear except the least significant. This digit indicates whether the original number is even or odd.
Note: Because they are "signed integers," the leftmost binary digit is used for the positive or negative sign.
Note: This answer assumes that integers are represented with 32 bits. According to my research, PHP represents 64-bit integers if the processor supports 64-bit instructions - in this case a% shift must be done%