~~如何做数学? [英] How does ~~ work as math.floor?
问题描述
我明白〜是一个有点不对的操作符,但是如何在数字上颠倒数位两次使其成为Math.floor
在Javascript中做什么~~(双波纹)描述了使用Math.floor与按位操作之间在Javascript中舍入数字的区别,但是我感兴趣的是如何完全颠倒这两次完成这一点。
I understand that ~ is a bitwise NOT operator, but how does inverting the bits on a number twice make it function as Math.floor What does ~~ ("double tilde") do in Javascript? describes the differences between using Math.floor vs bitwise operations to round numbers in Javascript, but I am interested in how exactly inverting the bits twice accomplishes this.
谢谢
推荐答案
从 规范 ,按位NOT,〜
- 让
expr
是评估 UnaryExpression 的结果。
- 让
oldValue
成为$ code> ToInt32(GetValue(expr))。 - 将使用逐位补码的结果返回到
oldValue
。结果是32位整数。
- Let
expr
be the result of evaluating UnaryExpression. - Let
oldValue
beToInt32(GetValue(expr))
. - Return the result of applying bitwise complement to
oldValue
. The result is a signed 32-bit integer.
ToInt32的定义
这里 。
32位整数 i
的补码为 i XOR 0xFFFFFFFF
。
The "complement" of a 32-bit integer i
is i XOR 0xFFFFFFFF
.
所以把这一切放在一起,你有 ~~我
,意思是
So put this all together and you have ~~i
as meaning
ToInt32(i) XOR 0xFFFFFFFF XOR 0xFFFFFFFF
// same as
ToInt32(i) XOR 0x00000000
// same as
ToInt32(i)
请记住负数的舍入方向上的差异。
Keep in mind the differences in rounding direction for negative numbers.
我个人喜欢使用 x | 0
over ~~ x
,因为相同结果的操作较少。
Personally I prefer using x | 0
over ~~x
because it involves fewer operations for the same result.
这篇关于~~如何做数学?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!