我见过很多人使用按位运算符来删除小数部分,或者使用按位运算符对数字进行四舍五入。
但是,我想知道这实际上是如何工作的?
let a = 13.6 | 0; //a == 13
let b = ~~13.6; // b == 13
我确实搜索过同样的内容。我能找到的最好的是this .
那里的人们正在谈论效率、优点和缺点。我对这实际上是如何工作的感兴趣?
All bitwise operations except unsigned right shift, >>>, work on signed 32-bit integers. So using bitwise operations will convert a float to an integer.
因此使用按位运算会将 float 转换为整数。但是如何实现呢?
最佳答案
使用|
,它的两个运算符通过NumberBitwiseOp转换为整数。操作,在两个算子上调用ToInt32
,其流程为:
The abstract operation ToInt32 takes argument argument. It converts argument to one of 232 integer values in the range -231 through 231 - 1, inclusive. It performs the following steps when called:
- Let number be ? ToNumber(argument).
- If number is NaN, +0, -0, +∞, or -∞, return +0.
- Let int be the Number value that is the same sign as number and whose magnitude is floor(abs(number)).
- Let int32bit be int modulo 2 ** 32.
- If int32bit ≥ 2 ** 31, return int32bit - 2 ** 32; otherwise return int32bit.
~
,或按位 NOT,does the same sort of thing ,通过在其运算符上调用 ToInt32
来实现。
使用x | 0
将删除 x
的小数部分(通过 ToInt32
)并且不翻转任何位,因此就好像只删除了小数部分。
使用~x
将删除x
的小数部分并翻转其所有位。使用 ~~x
会执行相同的操作,但翻转位两次,因此结果就像对原始表达式所做的所有操作都删除了小数部分。
关于javascript - 如何使用按位运算符删除小数部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61440398/