views:

177

answers:

3

I have the Python expression n <<= 1

How do you express this in PHP?

+4  A: 

It's the same operator in php. $n <<= 1;

Rob
+1  A: 

$n <<= 1; is valid php

sepp2k
+4  A: 

That statement is short for

n = n << 1;

the << operator is means a bitwise shift left, by n positions. Its counterpart is >>, which means shift right by n. To visualize, say you have the value 5, and you want to shift it left by 2 positions. In binary:

0000 0101 -> 5
shift left by 2:
0001 0100 -> 20

Basically, you shift all bits in the given direction, and pad with zeroes. More or less equivalent, if you don't have a bitwise shift operator (which is common in most, if not all languages), is multiplying by 2^n for shift left, and dividing by 2^n for shift right.

In the example, you can see that: 5 * 2^2 = 5 * 4 = 20.

Erik van Brakel