What does << in PHP mean?

Asked

Viewed 1,064 times

8

I came across the following calculation being assigned to a variable

(1103515245 * $num + 12345) % (1 << 31)

What do these mean <<?

2 answers

12


The operator << not only in php, but in several other languages, it is a Bit-a-bit operator.

What it does is shift the value to the left of the n times operator, where n is the value to the right of the operator. (Shift to the 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: http://php.net/manual/en/language.operators.bitwise.php

3

When the right-hand operator is 31, the shift-left operator is used with a very specific purpose: to find out if the left-hand operator is even or odd.

If even, the result of par << 31 will be 0. If odd, the result of impar << 31 will be -2147483648, the minimum value of whole 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 the integers are represented with 32 bits. According to my research, PHP represents 64-bit integers if the processor supports 64-bit statements - in that case a shift should be made << 63

  • I didn’t know this idea of using left shift to see if it’s even, but it’s easier (and less costly) to do ($a&1)==0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.