Question

How does this & (ampersand) bit-wise operator work?

$bcast = ip2long("192.168.178.255");
$smask = ip2long("255.255.255.0");
$nmask = $bcast & $smask;
echo long2ip($nmask); // Will give 192.168.178.0

Does it compare each several bit? I understand most of the magic in this snippet is done by long2ip(), but how does $nmask give the right value?

Edit: To clarify..
$bcast returns '3232281343'
$smask returns '3232281088'

1) Will the &-operator automagically turn this to their binary number?
2) As per my comment to AbraCadaver; what are some use cases where you want to use the bitwise operator?

Était-ce utile?

La solution

It compares each bit of the binary of the long and where both bits are 1 the result is 1, otherwise the result is 0. So for example:

first octet:

192    = 11000000
255    = 11111111
result = 11000000 = 192

last octet:

255    = 11111111
0      = 00000000
result = 00000000 = 0
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top