PDA

View Full Version : PHP Bitwise Woes


NetNessie
08-19-2008, 10:19 AM
It appears my absences from around here usually end when I hit a brick wall programming that Google can't easily answer.

Anywho, I've got a problem with the bitwise AND operation on floats in PHP.
Basically my operation goes:

echo (0xF4FF04F4 & 0xFF000000) >> 24;

With the first float being any float ranging from 0x00000000 to 0xFFFFFFFF. I tested the code in Python and it returned 244 as expected, except PHP turns around and returns a fantastically incorrect -12.

PHP behaves it self fairly well up until I use something larger than 7F. Once I write 7F, it starts getting into the negatives and all my operations go awry.

Any clues as to how I can convince PHP to behave?

Plagman
08-19-2008, 10:54 PM
There's no such thing as unsigned integers in PHP and so any hexadecimal constant that uses the 32nd bit will cause shifts to go to shit for various reasons. Enjoy.

NetNessie
08-20-2008, 01:05 AM
There's no such thing as unsigned integers in PHP and so any hexadecimal constant that uses the 32nd bit will cause shifts to go to shit for various reasons. Enjoy.

Well, that just sucks. Completely screws up one of my web applications.

Jiminator
08-20-2008, 10:30 AM
try (0xF4FF04F4 >> 24) & 0x000000FF
The first & is not necessary because the shift will delete the bits anyway
I am not familar with PHP so this may not actually work, but it would with C

Plagman
08-20-2008, 06:49 PM
That should work if you're really only interested in the eight higher bits of your initial value. After the shift the 24 higher bits will be full of bogus data so so really want to make sure you mask them out.

JonoF
09-18-2008, 04:18 AM
On a 64bit version of PHP you get 244, because the integer type size is dependent on your system architecture. 32bit gives -12. You could try using this code to grab just the biggest-endian byte of that dword:
echo ord(substr(pack('N', 0xF4FF04F4), 0, 1));

Jonathon