我可以在 Actionscript 3 中使用按位运算将负数转为正数吗?
有没有直接的方法如何使用 Actionscript 3 中的按位运算将负数变成正数?我只是想我在某处读到过,这比使用 Math.abs() 或乘以 -1 更快。或者我错了,这是经过一天的学习字节和按位运算后的一个梦想?
我看到的是按位 NOT
几乎可以解决问题:
// outputs: 449
trace( ~(-450) );
如果有人发现这个问题并且感兴趣 - 在 500 万次迭代中 ~(x) + 1
比Math.abs(x)
。
Is there a direct way how to turn a negative number to positive using bitwise operations in Actionscript 3? I just think I've read somewhere that it is possible and faster than using Math.abs()
or multiplying by -1
. Or am I wrong and it was a dream after day long learning about bytes and bitwise operations?
What I saw was that bitwise NOT
almost does the trick:
// outputs: 449
trace( ~(-450) );
If anyone find this question and is interested - in 5 million iterations ~(x) + 1
is 50% faster than Math.abs(x)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
按位取反后需要加一。这是二进制补码系统的属性。它与 Actionscript 无关(除了所谓的性能差异)。
因此,
(~(-450)+1)
给出450
和
(~(450)+1)
给出-450
。正如评论中所指出的,这个答案是为了回答问题而写的,以解决提问者实验中的一个小问题。这个答案并不认可这种技术用于一般软件开发。
You need to add one after taking the bitwise negation. This is a property of two's complement number system. It is not related to Actionscript (aside from the alleged performance difference).
So,
(~(-450)+1)
gives450
and
(~(450)+1)
gives-450
.As noted in comments, this answer is written in response to the question, to fix a minor issue in the question asker's experiment. This answer is not an endorsement of this technique for general software development use.
使用以下规则
Use the rule that says
如果使用二补码(通常是这种情况),则否定是补码然后加 1:
是否更快取决于编译器执行的优化。如有疑问,请进行测试。
If two-complement is being used (usually the case), negation is complement then add 1:
Whether it's faster depends on what optimisations the compiler performs. When in doubt, test.
否定本身就是一个运算符,即一元
-
运算符。使用它与使用按位运算一样快,并且可以节省大量输入。不执行乘法。
如果您需要速度,并且您不知道数字是负数还是正数,那么三元运算符
?:
比引入Math.abs() 的函数调用开销更快
。Negation is an operator all unto itself, the unary
-
operator. Using this is just as fast as using bitwise operations and saves you a lot of typing.No multiplication is performed.
If speed is your need, and you don't know if the number is negative or positive, the ternary operator
?:
is faster than introducing the function-call overhead ofMath.abs()
.基本上,数字 2' 的补码是相反符号的数字。
Basically numbers 2' complement is the number in opposite sign.
试试这个:
最后,你所需要的就是这个:
Try this:
In the end, all you need is this: