Using bitwise 'and', 'or' operators(Python)

vegaseat 0 Tallied Votes 277 Views Share

Just some interesting applications of the bitwise and (&), or (|) operators. You might find some other uses.

''' bitwise_and_or.py
some interesting applications of bitwise and (&), or (|)
tested with Python27  by  vegaseat  19apr2015
'''

def is_odd(n):
    '''
    symbol & is the bitwise 'and' operator
    use n & 1 to check if n is odd or even
    return True if n is an odd integer, else False
    '''
    if n & 1:
        return True
    else:
        return False

def next_odd(n):
    '''
    symbol | is the bitwise 'or' operator
    use n | 1 to turn an even integer into its next odd integer
    does not change odd integers
    '''
    return n|1

# testing ...
print(is_odd(21))  # True
print(is_odd(22))  # False

print(next_odd(8))  # 9
print(next_odd(7))  # 7
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This is how the exclusive or behaves ...

def next_odd_even(n):
    '''
    symbol ^ is the bitwise 'exlusive or' operator
    use n ^ 1 to turn an even n into the next odd integer
    and an odd n into the previous even integer
    '''
    return n^1


# testing ...
print(next_odd_even(8))  # 9
print(next_odd_even(7))  # 6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.