echo 50 >> 4;
Output:
3
Does anyone know why it outputs 3?
echo 50 >> 4;
Output:
3
Does anyone know why it outputs 3?
>> is the binary right-shift operator.
Your statement shfits the bits in the numeric value 50, 4 places to the right. Because all integers are represented in 2s complement, this equals 3. And easy way to remember this is that one shift to the right is the same as dividing by 2, and one shift to the left is the same as multiplying by 2.
it shifts the bits down 4 places.
50 in binary is 110010.
shifted down 4 places is 11, which is 3
The >>
operator is called a binary right shift operator.
Shifting bits to the right 4 times is the same as dividing by two, four times in a row. The result, in this case would be 3.125
. Since 50 is an int, bit shifting will return the floor of this, which is 3
.
Put another way, 50
is 0b110010
in binary. Shifted 4 times we have 0b11
, which is 3
in decimal.
As documented on php.org, the >>
operator is a bitwise shift operator which shifts bits to the right:
$a >> $b - Shift the bits of $a $b steps to the right (each step means "divide by two")
50 in binary is 110010
, and the >>
operator shifts those bits over 4 places in your example code. Although this happens in a single operation, you could think of it in multiple steps like this:
00011001
00001100
00000110
00000011
Since binary 11
is equal to 3
in decimal, the code outputs 3.
It's called a right shift. 'The bits of the left operand are shifted right by the number of positions of the right operand. The bit positions vacated on the left are filled with the sign bit, and bits shifted out on the right are discarded.'
Information can be found on it here: http://php.comsci.us/etymology/operator/rightshift.php