1

In PHP, if I run the following simple program

$number = 9;
var_dump( ~ $number );

my output is

int(-10)

This is confusing to me. I thought ~ was the bitwise NOT operator. So I was expecting something like.

if binary 9 is     00000000000000000000000000001001 
then Bitwise NOT 9 11111111111111111111111111110110

Meaning ~9 should come out as some ludicrously large integer like 4,294,967,286.

What subtly of precedence, type coercion, or something else am I missing here?

1
  • It looks like it's being returned as a signed number, in which case -10 is correct. Commented Sep 12, 2013 at 2:11

1 Answer 1

4

Your output is defaulting to a signed int - wrap it in decbin to get a binary representation.

Consider:

$number = 9;
var_dump(  bindec(decbin(~ $number)) );

With two's compliment, the MSB of a signed binary number becomes 0-MSB, but every other bit retains its respective positive values.

So for argument's sake (an 8-bit example),

Binary 9: 0000 1001
Inverse:  1111 0110

This results in (-128) + 64 + 32 + 16 + 4 + 2 = -10, so PHP is calculating correctly, its just applying two's compliment to the MSB.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for good information, but I'm not sure I follow that — are you saying it's being correctly converted to 11111111111111111111111111110110, and then to 4,294,967,286, but because of integer wrap around it ends up at -10?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.