我正在将一些传统的Pascal转换为JavaScript.我需要多个两个32位有符号整数.
在下面的示例循环中,一些乘法将导致溢出并将给出负数.这是故意的.我需要在与遗留系统匹配的末尾重现相同的最终数字x.
如何在JavaScript中实现此目的以获得相同的结果?
以下是一些示例代码:
var x = new Number(some value); // I need this to be a 32-bit signed integer
var y = new Number(some value); // I need this to be a 32-bit signed integer
for (var i=0; i<100; i++) {
x = x * y;
}
return x;
Run Code Online (Sandbox Code Playgroud)
Ada*_*ppe 10
Javascript的按位运算符实际上将值转换为常规整数.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators这个事实被像asm.js这样的东西用来强制类型,你也可以自己做.诀窍是在数字的末尾加上| 0以强制它为32位
function test() {
var x = 255|0; // |0 does the type coercion
var y = 255|0; // not strictly necessary at this var decl but used for explicitness
for (var i=0; i<5; i++) {
x = (y * x)|0; // parens needed because |'s precedence
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
我用几个数字运行它并得到与Firefox中的C相同的结果..没有机会在IE中测试,但我很确定这种行为是在ECMAscript规范中,所以它应该工作.
| 归档时间: |
|
| 查看次数: |
3781 次 |
| 最近记录: |