Generic-user-small Arpan Chinta 4 posts

In the second episode (Sharing Behavior), you have this code


def self.is_even?(num)
  (num & 1) == 0
end

I’ve never used this “&” operator before. What does it do?


10 & 2 => 2
11 & 2 => 2
12 & 2 => 0

Could you tell me a little bit about what this operator does.

In the pickaxe book you mention that it is a “Bitwise AND” (page 420) operator. I have no idea what that means. :-)

 
Generic-user-small Ian Hunter 1 post

&& is a logical AND, & is a bitwise operator. Let’s do some binary math (don’t look so excited)

10 & 2 is actually

00001010
00000010 &
--
00000010

For each bit, it does an AND operation (which produces 1 when both inputs are 1, 0 all other times).

To answer your section portion, let’s look at the binary for 10, 11 and 12:

10: 00001010
11: 00001011
12: 00010100 # there’s nothing in the binary 2’s spot, therefore:

00010100
00000010 &
--
00000000

Make sense?

 
Generic-user-small Arpan Chinta 4 posts

Yes, I got it. Thanks.

3 posts, 2 voices