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.
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
&
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
x & y
is a number where for all i
the i
th bit is 1 if and only if the i
th bit of x
and the i
th 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With