What is the ~ (til) operator for in PHP?

Asked

Viewed 432 times

20

What is the operator for ~ (til) in PHP?

I’ve seen things like:

echo ~PHP_INT_MAX

Until then I thought it was to "reverse" a number to negative, or something like that, but with the tests I saw that I was wrong.

Example:

echo ~2; //Imprime -3

echo ~5; //Imprime -6

1 answer

21


It’s the negation operator bit to bit. That is, it reverses the value of all bits of the data in question. Those who were 0 saw 1 and those who were 1 saw 0. His name is bitwise not. Do not confuse with the logical negation operator !.

It does not negative the number, for this there is the unary operator of negative.

Then the number 2 can be represented in binary by

00000010 //isto é 2 em binário

denying (reversing) the bits stays:

11111101 //isto é -3 em binário

I did with 8 bits to simplify, probably the number would have more bits. If you turn this number to decimal, you will get this -3.

If you analyze, 2 is the third number of positives, and 3 is also the third number of negatives. There is an inversion in this sense, but the fact of going from positive to negative is a question of the type of data.

Its usefulness is great in some scenarios, but most programmers can’t see when it can be used to avoid wild math. Simple is often harder to see.

When you see it:

E_ALL & ~E_STRICT & ~E_WARNING & ~E_NOTICE

Read it like this: turn on all the ALL errors, but NOT the mistakes that are STRICT, NEITHER THE WARNING and also not the NOTICE. This is an expression that will result in a number that will be used properly by PHP to understand what is on or off. The human understands as I have shown, but to select, the code will deal with the bits existing in an appropriate combination.

Documentation.

Browser other questions tagged

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