Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 258
ab217 Avatar asked Nov 06 '10 20:11

ab217


3 Answers

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
like image 81
Jack Avatar answered Nov 19 '22 14:11

Jack


& 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

like image 24
Alan Geleynse Avatar answered Nov 19 '22 15:11

Alan Geleynse


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.

like image 3
sepp2k Avatar answered Nov 19 '22 14:11

sepp2k