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
Add a ment  | 

2 Answers 2

Reset to default 7

won'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