6 Mind-Blowing Uses Of Bitwise Operations That You Probably Never Knew Existed
Become An Efficient Engineer With These Use Cases
1. Checking If A Number Is Odd Or Even (Parity)
The conventional way to check if a given number is odd or even is to check the remainder when the number is divided by 2.
If the remainder is 0, the number is even.
If it is not, the number is odd.
def check_parity(num):
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Using Bitwise Operations
A bitwise AND
(using &
operator in Python) operation can be used to check the parity of a number.
If a number is even, its binary representation ends in 0
. For example, 10
is 2
in decimal, an even number.
If it is odd, it ends in 1
. For example, 11
is 3
in decimal, an odd number.
When we use the AND
operation on the number and 1
, if the least significant bit of the result is 0
, then it is an even number.
10 (2 in decimal)
& 01 (1 in decimal)
----
00 -> Falsy value -> Even number
11 (3 in decimal)
& 01 (1 in decimal)
----
01 -> Truthy value -> Odd number
Le…
Keep reading with a 7-day free trial
Subscribe to Into AI to keep reading this post and get 7 days of free access to the full post archives.