Javascript & PHP Xor equivalent

牧云@^-^@ 提交于 2019-12-17 16:39:59

问题


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:


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.



来源:https://stackoverflow.com/questions/24154381/javascript-php-xor-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!