# [Tutor] Bitwise &

Alan Gauld alan.gauld at btinternet.com
Wed Oct 14 19:35:36 EDT 2015

```On 14/10/15 21:47, ਨਿਹੰਗ ਪੰਜਾਬੀ wrote:
>   'if (n & 1)'  below works but I don't understand why/how.  Kindly help.

Do you understand what bitwise & does?
It takers the logical AND of each bit in the two operands.

So, keeping it simple with 2 digit numbers we get

0 = 00
1 = 01
2 = 10
3 = 11

Notice that the second bit in each odd number is a 1.

So anding two odd numbers results in the last two
bits both being 1 and (1 AND 1) is always 1.

So long as any bit is 1 the overall result of (X & Y)
will be True, only all zero will be False.

So you are guaranteed that two odd numbers ANDed
together will be True

>
> ==============
>>>> def fn(n):
> ...     if (n & 1):
> ...         print "n is odd"
> ...     else:
> ...         print "n is even"

So this will indeed work.

However its not necessarily good style since it is
not obvious how it works unless you understand bitwise
operations so arguably,

def f(n):
if n%2 == 0 :
print 'n is even
else...

Would be clearer.

Although that's just a tad subjective.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

```