Ruby: What does the snippet: (num & 1) == 0 exactly do?

与世无争的帅哥 提交于 2019-12-20 09:58:46

问题


I was watching a metaprogramming video from PragProg, and Dave Thomas showed this snippet of code:

module Math
  class << self
    def is_even?(num)
      (num & 1) == 0 # What exactly is going on here? Particularly (num & 1)
    end
  end
end

puts Math.is_even? 1 # => false
puts Math.is_even? 2 # => true

Now I understand what is going on here, but I don't know what exactly is happening with the (num & 1) part of the Math.is_even? class method. I know it is a bitwise operation but that is about it. Can someone explain to me what is going with that line of code? Thanks.


回答1:


& is a bitwise AND operator. Doing (num & 1) checks if the last bit (least significant bit) of the number is set. If it is set, the number is odd, and if it is not set, it is even.

It is just a fast way to check if a number is even or odd.

You can see a list of the ruby bitwise operators here: http://www.techotopia.com/index.php/Ruby_Operators#Ruby_Bitwise_Operators




回答2:


It's a little trick: every binary number that has the least significative bit to 0 is even and odd otherwise. This because the powers of two are 1,2,4,8,16,... so what happens is that when you do bitwise AND with 1 you obtain 0 if the least significative bit was 0 and 1 otherwise. So you can easily recognize if a number if even by doing that.

Of course this works just because the arithmetic used in CPUs is binary, otherwise it would be just crap..

just an example

161 = 10100001 &
1   = 00000001
--------------
      00000001 -> odd

viceversa

84  = 01010100 &
1   = 00000001 
--------------
      00000000 -> even



回答3:


x & y is a number where for all i the ith bit is 1 if and only if the ith bit of x and the ith bit of y are 1 and 0 otherwise.

Since 1 is the number where only the last bit is 1, x & 1 is 1 if the last bit of x is 1 and 0 otherwise.

Since the last bit of a number is 1 if it's odd and 0 if it's even, checking whether x&1 is 0 is equivalent to checking whether a number is even.



来源:https://stackoverflow.com/questions/4115045/ruby-what-does-the-snippet-num-1-0-exactly-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!