Can someone tell me why I'm getting 4 as the outcome? Should 3 be printing instead because the code is satisfied in the If section.
a = 15
if a&5 == 0:
print('3')
elif a% 5 == 0:
print('4')
else:
print('5')
4 Answers 4
& is bitwise AND and works like this:
15 & 5
1111
& 0101
------
0101 != 0
Comments
You are comparing the bits of 15 with the bits of 5, resulting in the ones they have in common.
1111 & 101 => 101
so the result is 5, not 0.
Comments
The "&" operator is a Bitwise AND so in your code it is like:
1111 & 0101 = 0101
That means
15 and 5 = 5
So the first condition can not be true and you'll get 4 in output because the reminder of 15/5 is 0.
Comments
If you want to check LSB then you should do "and" with 1 and check the result if it's 1 then LSB is 0 else LSB is 1
15&5will evaluate to5and5never equals to0.