Understanding ~ Operator

75 views Asked by At

I am learning Bitwise Operators and for that I pulled out an article on tutsplus. Well, it is written quite nicely. I could understand the & and | operator but the ~ is messing things up. For example, as stated there in the article:

In fact, just as ! flips a boolean from true to false or vice versa, the ~ operator reverses each binary digit in an integer: from 0 to 1 and 1 to 0.

The article has assumed that the OS is storing integer as 1 byteor 8 bits. I am following it. I am using PHP for experimenting. The code's below:

$b = 12;
$NOR = ~$b;

/*
* ------------------------
* | $b | 0 0 0 0 1 1 0 0 | = 12
* ------------------------
* |  ~ | 1 1 1 1 0 0 1 1 | = 243 as 1 + 2 + 16 + 32 + 64 + 128 = 243
* ------------------------
* Each digit will be inverted.
*/

echobr($NOR);

Even if we consider that $bwas stored as 32 bit. Then the inverted value should be > 243. Instead, it returns -13. echobr() is the function I defined.

If it can be explained, it will be very helpful.

1

There are 1 answers

3
Tian Li On BEST ANSWER

$b = 0000 0000 0000 0000 0000 0000 0000 1100

~$b = 1111 1111 1111 1111 1111 1111 1111 0011 = -13

Note that PHP uses the two's complement representation which means that the most significant bit is the sign bit, here '1' refers to '-'. You can read more about the sign bit here Sign bit-Wikipedia.

As a matter of fact, for any signed integer in PHP, -$i == ~$i + 1