Reputation: 75
I was browsing through an open source project and came across this python method. I am aware on how the & and << bitwise operators work, but I am not sure how the if else statement works in this case. I can say int = 2 and position is = 1 and the if statement results to 2 (10 base 2), but what does this if statement compare 2 to? and how would I evaluate to the else statement?
def get_bit(int, position):
if int & (1 << position):
return '1'
else:
return '0'
Upvotes: 1
Views: 2664
Reputation: 26609
It tests if the result is falsey.
In Python, values such as False
, None
, 0
, empty strings, empty lists, etc. are "falsey", while others are truthy. In this case, it's effectively comparing the result of the bitwise AND with zero.
if (int & (1 << position)) != 0: # same thing
Upvotes: 3
Reputation: 26278
The if statement checks the "truthiness" of the expression. For instance, if you had:
if some_expression:
...
That's equivalent to writing:
if bool(some_expression):
...
You don't have to call bool()
explicitly, but there's relatively little harm in doing so if you want to. Some programmers consider it bad style, since it's not strictly necessary.
It's not necessary because every expression in Python has a truthiness value. The things that are false are:
False
(obviously)None
Custom classes can also declare their truthiness by implementing __nonzero__.
So, in the case of your specific question, the "if" part of your if/else will be executed even if the expression evaluates to 2, since any non-zero int will be considered True in a boolean context.
Upvotes: 1