views:

142

answers:

2

I don't understand why this statement in PHP echos 'whaaa?' -- (0x0F | 0xF0) should be 0xFF no?

if((0x0FFFFFFF | 0xF0FFFFFF) != 0xFFFFFFFF) echo 'whaaa?';
+1  A: 

Test it by writing var_dump((0x0FFFFFFF | 0xF0FFFFFF))

chelmertz
Good call on giving information on how to find out, but it would be nice if you included an explanation as to the particular behavior.
Adam Davis
I get int(-1) which in 2's complement should be represented as 0xFFFFFFFF right?
Brad
+1  A: 

The result of this script:

var_dump((0x0FFFFFFF)); 
var_dump((0xF0FFFFFF)); 
var_dump((0x0FFFFFFF | 0xF0FFFFFF)); 
var_dump((0xFFFFFFFF)); 
var_dump(((0x0FFFFFFF | 0xF0FFFFFF)) != (0xFFFFFFFF));

is

int(268435455)
float(4043309055)
int(-1)
float(4294967295)
bool(true)

PHP converts hexadecimal numbers larger than 31 bits into floats, as an integer is signed, and can therefore only hold 31 positive bits.

Hexadecimal numbers are unsigned, so the conversion makes sense.

The first "or" operation converts the float into an integer, as it doesn't make sense to perform an "or" on a float. So PHP converts the float to an int for the or, the result is an int, but the next hexadecimal conversion is a float, and the values are not the same.

To convert the float to a integer in a bitwise fashion, OR it with 0x0:

var_dump((0xFFFFFFFF | 0x0)); 
var_dump(((0x0FFFFFFF | 0xF0FFFFFF)) != (0xFFFFFFFF | 0x0));

results in

int(-1)
bool(false)
Adam Davis
Ah, so is there a way to make 0xFFFFFFFF not be converted to a float? I guess what I'm asking is can you not create a negative integer in hex?
Brad
PHP's internal function does not convert numbers larger than 32 bits to integers since 4.1: http://www.php.net/manual/en/function.hexdec.php - there are solutions in the comments on that page.
Adam Davis
Alternately, just | it with 0, see my answer edit.
Adam Davis
It's worthwhile studying the bitwise operators page in the PHP manual ( http://php.net/manual/en/language.operators.bitwise.php ) because the way PHP does things is different than many other languages, especially in regards to converting variables into integers prior to the operation.
Adam Davis
Thanks, this really helped my understanding.
Brad
Glad to see this helped.
Adam Davis