admin管理员组文章数量:1291698
I have a formula in JS that uses the bitwise NOT operator.
~~(n/m + 0.5) * m;
How do I write the same expression in ruby? There is no bitwise NOT operator in ruby.
I have a formula in JS that uses the bitwise NOT operator.
~~(n/m + 0.5) * m;
How do I write the same expression in ruby? There is no bitwise NOT operator in ruby.
Share asked Apr 5, 2011 at 17:52 Aen TanAen Tan 3,3456 gold badges35 silver badges53 bronze badges 1- 1 There is a bitwise NOT operator in ruby: ~200 #=> -201 techotopia./index.php/Ruby_Operators – Automatico Commented Aug 4, 2012 at 17:04
2 Answers
Reset to default 7won't this help? http://www.techotopia./index.php/Ruby_Operators#Ruby_Bitwise_Operators
~ Bitwise NOT (Complement)
I believe the same expression in Ruby would be (n/m + 0.5).to_i * m
, or, alternatively, Integer(n/m + 0.5) * m
.
It looks like the doubled bitwise plement there is really being used to truncate the decimal part of the calculation, in order to pute the nearest n such that n is a multiple of m. (In another language, I would say "convert to integer", but Javascript has a unified arithmetic type.)
Update: Mladen Jablanović suggests a cast, and yes, if both m and n are Fixnum, it's needed. In Ruby 1 / 3 is 0 but in JS it's 0.333... Here is a refined suggestion:
(n.to_f / m).round * m
本文标签: javascriptBitwise NOT in rubyStack Overflow
版权声明:本文标题:javascript - Bitwise NOT in ruby - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741533414a2383892.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论