3

I have a javascript code:

var c = 267414715;
var d = c ^ ("0x81BE16CD");

Result is -1907459466

http://jsfiddle.net/4N3JY/1/

I can't seem to get a PHP equivalent. Have tried the following:

<?php    
$c=267414715;

$d=$c ^ hexdec("0x81BE16CD");
echo "With hexdec: $d\n";

$d=$c ^ base_convert("0x81BE16CD", 16, 2);
echo "With base_convert(2): $d\n";

$d=$c ^ base_convert("0x81BE16CD", 16, 10);
echo "With base_convert(10): $d\n";
?>

Output:

With hexdec: 2387507830
With base_convert(2): 9223372036587361092
With base_convert(10): 2387507830

Can someone please point out the correct equivalent code, and also explain how the different versions (base_convert / hexdec / "correct" equivalent differ in their working).

1 Answer 1

1

2387507830 == -1907459466 when using unsigned integers (look at the bit values of the least significant bits)

2387507830 = 0000 0000 0000 0000 0000 0000 0000 0000 1000 1110 0100 1110 0111 1010 0111 0110 -1907459466= 1111 1111 1111 1111 1111 1111 1111 1111 1000 1110 0100 1110 0111 1010 0111 0110

your problem is a 32 bit roll over. To compensate you can simply & 0xffffffff which will 0 out the most significant 32 bits, and make both answers the same.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, Yes, I too was experimenting with different values and found out problem lies only when mask has leading 1 (in binary representation). Can you clarify & 0xffffffff exactly where? In the mask? I want the PHP code to behave same as the JS code.
var d = (c ^ ("0x81BE16CD")) & 0xffffffff; The idea is to 0 out the upper 32 bits, & states that the result should only be 1 if both the operands are 1, since one operand will always be 0 in the upper 32 bits the result for these bits will always be 0
Hmm. Well I have to make php code behave like the JS one. Also, I felt problem is when msb of c & mask are different I think. Thanks for your help. Am trying to put things together with your answer.
The problem is that for whatever reason, your PHP implementation has 32 bit integers and your javascript has 64 bit. Both operands are 32 bit numbers, so javascript is considering each operand to be 0x0000000081BE16CD and 0x00000000FF06CBB. 0 xor 0 = 1.
Thanks, yes, that makes sense now. Figuring out how to use 64 bit ints in PHP now (by any chance you would know a simple trick)?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.