使用按位或0到地板了一些 [英] Using bitwise OR 0 to floor a number

查看:109
本文介绍了使用按位或0到地板了一些的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位同事偶然发现地板浮点数的方法使用按位或:

  VAR一个= 13.6 | 0; //一个== 13

我们都在谈论它,不知道几件事情。


  • 它是如何工作的?我们的理论是,使用这样的操作者投射的数量的整数,从而去除小数部分

  • 是否有过做 Math.floor 什么优势?也许这是一个快一点? (双关语并非意)

  • 它有什么缺点?也许不会在某些情况下,工作的?清晰度是一个明显的例子,因为我们必须弄清楚,和好,我书面方式这个问题。

感谢。


解决方案

  

它是如何工作的?我们的理论是,使用这种操作注塑
  数的整数,从而去除小数部分


除了无符号的右移,&GT所有位运算;>> ,签署的32位整数的工作。因此,使用位运算将浮点转换为整数。


  

它是否有过做任何Math.floor优势?也许这是一个有点
  更快? (双关语并非意)


http://jsperf.com/or-vs-floor/2 稍快似乎


  

它有什么缺点?也许不会在某些情况下,工作的?
  清晰度是一个明显的例子,因为我们必须弄清楚,和好了,
  我书面方式这个问题。



  • 将无法通过JSLint的。

  • 32位有符号整数只有

  • 比较奇怪的行为: Math.floor(NAN)=== NaN的,而(NAN | 0)=== 0

A colleague of mine stumbled upon a method to floor float numbers using a bitwise or:

var a = 13.6 | 0; //a == 13

We were talking about it and wondering a few things.

  • How does it work? Our theory was that using such an operator casts the number to an integer, thus removing the fractional part
  • Does it have any advantages over doing Math.floor? Maybe it's a bit faster? (pun not intended)
  • Does it have any disadvantages? Maybe it doesn't work in some cases? Clarity is an obvious one, since we had to figure it out, and well, I'm writting this question.

Thanks.

解决方案

How does it work? Our theory was that using such an operator casts the number to an integer, thus removing the fractional part

All bitwise operations except unsigned right shift, >>>, work on signed 32-bit integers. So using bitwise operations will convert a float to an integer.

Does it have any advantages over doing Math.floor? Maybe it's a bit faster? (pun not intended)

http://jsperf.com/or-vs-floor/2 seems slightly faster

Does it have any disadvantages? Maybe it doesn't work in some cases? Clarity is an obvious one, since we had to figure it out, and well, I'm writting this question.

  • Will not pass jsLint.
  • 32-bit signed integers only
  • Odd Comparative behavior: Math.floor(NaN) === NaN, while (NaN | 0) === 0

这篇关于使用按位或0到地板了一些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆