Unexpected result of a bitwise PHP operation

The operation 1539 | 0xfffff800returns -509in JavaScript and Python 2.7. In PHP, I get 4294966787.

Does anyone know why and can explain this to me. I would really like to know how I get the expected result in PHP.

+4
source share
1 answer

1539 | 0xfffff800 = 4294966787 (= 0xFFFFFE03) This is completely correct. So PHP is right.

If you want to have both positive and negative integers, you need some mechanism to determine if the number is negative. This is usually done using a 2-complement number. You can negate a number by simply inverting all the bits of the number, and then add 1 to it. To avoid ambiguity, you cannot use all bits of an integer variable. In this case, you cannot use the most significant bit. The most significant bit is reserved as a sign bit. (If you do not, you will never know if your number is a large positive number or a negative number.)

For example, with an 8-bit integer variable, you can represent numbers from 0 to 255. If you need signed values, you can represent a number from -128 (1,000,000 binary) to +127 (0111 1111).

32- . Python JavaScript , , -, 32- , . . , . PHP- 64-, 32 . ( 63) , PHP . , , 32 63 1s, ...

+1

All Articles