Page 1 of 1

Very whacky results Bitshifting in PHP. PLEASE help!

Posted: Sat Oct 22, 2005 12:16 pm
by DRT2
Hi,

I'm trying to do some bit comparison in PHP. The code used is a ^= b which is suppose to extract bits which are in either A or B but not in both A and B.

This seems to work perfectly for numbers that match in binary length, but numbers that are shorter or longer return very strange results. See below.

11001001001100101101100101001010=3375552842 (original first number a A)
1111010010101100101110000000000 =2052480000 (original second number B)

1001100100110110111101010110110 =-1285257910 (PHP Result, negative?)
10110011011001001000010101001010=3009709386 (VB.net Result)
10110011011001001000010101001010=3009709386 (Done manually by inserting a leading 0 in front of binary b)

So what is PHP actually doing here? I've spent half the night last night and still cant figure it out!

Thanks a bunch!
DRT

Posted: Sat Oct 22, 2005 3:50 pm
by feyd
how are you having php compute this result?

Posted: Sat Oct 22, 2005 4:06 pm
by DRT2
ok. figured out a part of it but i'm still stuck. this happens because i'm trying to overflow the signed integer.

the original equation was something like a ^= b. to take out bits which are in A or B but not in both A and B.

for the sake of getting things clear, lets look at a new variable z.

when i try to overflow z, it turns into something else, but I don't what formula or how its turned into that number.

ex:

$z=3375552842;
$z ^=0;
print $z;
-------
z=-919414454

But how does it go from

11001001001100101101100101001010 (3375552842)
110110110011010010011010110110 (-919414454, may need to add 1 at end to make it negative)

I'm basically trying to move some PHP code to vb.net. and while VB.net computes the A ^= B (a xor b) correctly, PHP doesn't because it can't handle integers larger than 2147483647. But how is it coming up with the strange -919414454 and how can I come up with the same in vb.net?

Thanks!
DRT

Posted: Sat Oct 22, 2005 4:46 pm
by feyd
integers above the 0x7FFFFFFF mark are stored in negative form (which is the two's complement of the positive form). Here's how two's complement is computed

Code: Select all

11001001001100101101100101001010 (3375552842)
00110110110011010010011010110101 (inverted)
00110110110011010010011010110110 (add one)

Posted: Sat Oct 22, 2005 4:58 pm
by DRT2
amazing! i almost tore all my hair out trying to figure this out and it was simply inverted.

thank you VERY VERY much for your help.