See the lottery code for <TFC2017/>
~~23.5 // 23
Why can ~
operators round numbers?
伊谢尔伦2017-06-28 09:31:08
via ToInt32. Its function is to flip the binary form of the operand bitwise. So two ~~ connected together are equivalent to the following operations:
Perform ToInt32 on the operand
Flip by bit
Bitwise flipping again actually still uses the absolute value rounding of ToInt32
In addition, there is a trick about the ~ operator that is quite practical: the value of
~(-1)
is0
, and-1
is the only value that returns a false value after the~
operation (including other ones Special values such as NaN, {}, [], etc. will not return false values) If the indexOf function of strings and arrays fails to search, it will return-1
. At this time, you can useif(~str.indexOf('str ')) // To indicate that
is found is more elegant than judging>= 0
or!= -1
, and it is similar to using!!
to judge non-false valuesAuthor: mdluo
Link: https://www.zhihu.com/questio...
Rounding converts floating point numbers into 32-bit binary integers, so bit operations that can restore the state can be rounded, such as 23.5 >> 0 //23
, 23.5 >> 0 //23
.