[英]Why does the '<<' operator sometimes behave differently in Javascript and PHP?
Take the following code snippet: 请使用以下代码段:
<script>
var x = 25;
document.write(x << 9);
</script>
<?php
$x = 25;
echo ($x << 9);
?>
This outputs: 12800 12800
输出:
12800 12800
OK. 好。 Normal so far... Now lets try this:
正常到目前为止......现在让我们试试这个:
<script>
var x = 12345678;
document.write(x << 9);
</script>
<?php
$x = 12345678;
echo ($x << 9);
?>
This time the output is 2026019840 6320987136
这次输出是
2026019840 6320987136
Why are the latter two values different? 为什么后两个值不同? And, most importantly (to me), how do I get the PHP implementation to do what the Javascript implementation does?
而且,最重要的是(对我而言),如何让PHP实现执行Javascript实现的功能? In other words, I want my PHP code to output 2026019840 instead of 6320987136
换句话说,我希望我的PHP代码输出2026019840而不是6320987136
use (x << 9) % 0x100000000
or its PHP equivalent. 使用
(x << 9) % 0x100000000
或其等效的PHP。 (or what you just said) (或你刚才说的)
PHP is giving you a 64 bit result. PHP给你一个64位的结果。 Javascript is just giving you the lower 32bits.
Javascript只是给你较低的32位。 If you use
(x << 9) & 0xFFFFFFFF
in PHP you'll get the low 32 bits. 如果在PHP中使用
(x << 9) & 0xFFFFFFFF
,则会得到低32位。
you may run into problems with the sign bit though. 你可能会遇到符号位问题。 Try
(23456789 << 9)
试试
(23456789 << 9)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.