javascript - 如何使用按位运算符删除小数部分?

标签 javascript floating-point bit-manipulation

我见过很多人使用按位运算符来删除小数部分,或者使用按位运算符对数字进行四舍五入。

但是,我想知道这实际上是如何工作的?

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:

  1. Let number be ? ToNumber(argument).
  2. If number is NaN, +0, -0, +∞, or -∞, return +0.
  3. Let int be the Number value that is the same sign as number and whose magnitude is floor(abs(number)).
  4. Let int32bit be int modulo 2 ** 32.
  5. 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/

相关文章:

javascript - 全日历在当前月份的月 View 中的错误日期显示事件

c - 这两个char数组的值有什么区别?

c++ - 如何设置整数的前三个字节?在 C++ 中

assembly - 浮点按位运算的用处

javascript - 数组推送中的“for”循环(javascript)

javascript - 数组数组中对象的总和值

javascript - 窗口确认确定/取消对话框中的奇怪行为?

floating-point - Erlang 和大数

c++ - while循环中的浮点比较与模数

c++ - 从 unsigned char 生成十六进制