【发布时间】:2012-05-06 21:33:25
【问题描述】:
我试图通过对位进行操作来了解加、减、除和乘的方法。
由于在事件发生后会运行许多计算,因此有必要在我的 JavaScript 程序中进行一些优化。
通过使用下面的代码作为参考,我能够理解进位包含 &ing 值。然后通过执行 XOr 将 sum var 设置为每个 n1 / n2 变量中不匹配的位。
这是我的问题。;) 将 (n1 & n2)
function add(n1,n2)
{
var carry, sum;
// Find out which bits will result in a carry.
// Those bits will affect the bits directly to
// the left, so we shall shift one bit.
carry = (n1 & n2) << 1;
// In digital electronics, an XOR gate is also known
// as a quarter adder. Basically an addition is performed
// on each individual bit, and the carry is discarded.
//
// All I'm doing here is applying the same concept.
sum = n1 ^ n2;
// If any bits match in position, then perform the
// addition on the current sum and the results of
// the carry.
if (sum & carry)
{
return add(sum, carry);
}
// Return the sum.
else
{
return sum ^ carry;
};
};
上面的代码按预期工作,但它不返回浮点值。我必须将总数与浮点值一起返回。
有没有人可以使用上面的函数来帮助我处理浮点值?是否有明确解释我要查找的内容的网站?我已经尝试搜索最后一天是如此,找不到任何可以查看的内容。
我从这个资源中得到了上面的代码。 http://www.dreamincode.net/code/snippet3015.htm
提前谢谢!
考虑一下左移到 1 的位置是乘以 2。
通过 &ing 像这样:carry = (n1 & n2) 进位变量将保存由 n1 和 n2 中的匹配位置编译而成的二进制字符串。因此,如果 n1 为 4 且 n2 为 4,则它们都具有相同的值。因此,通过将两者结合起来并右移到 1 索引将乘以 4 x 2 = 8;所以进位现在等于 8。
1.) var 进位 = 00001000 =8 & 00001000 =8
2.) 进位 = 现在保存单个值 00001000 =8
左移将乘以 8 x 2 =16,或 8 + 8 = 16
3.)carry = 进位
4.) 进位现在保存一个值 00010000 = 16
我仍然找不到任何有关使用浮点值的信息。如果有人有什么,请发布链接。
【问题讨论】:
-
你真的不会通过编写更多代码来提高 FP 操作的速度。 FPU 已经高度优化并且与主 ALU 异步。您最好自己尝试改进计算。
标签: javascript floating-point bit-manipulation