Bit manipulation cheat sheet | Python
Table of contents
Why bit manipulation? ๐ญ
- Bit manipulation introduces low-level control and speeds up code execution, thus improving performance.
Cheatsheet | python ๐
# =================
print(~13 & 1) # op: 0, odd num
print(~12 & 1) # op: 1, even num
# =================
# Left shift and Right shift
x << n == x * pow(2, n)
x >> n == x / pow(2, n)
# =================
# Power of 2 -> MSB of the number should be 1
# Eg: n=8(1000b), n-1=7(0111b)
# so n & (n-1) = 0
(n & (n-1))==0 # power of 2
# =================
# xor operator of the same number is 0
# simplifying a^b^b =a
# b^b -> 0
# a^0 -> a
nums = [4,1,2,1,2]
res = 0
for num in nums:
res = num ^ res # will be able to store unique value
return res # 4
# =================
# finding missing numbers in an array. Again use xor.
# Eg: [0, 1, 3].
# xor = 3.
# 0^1^2^3^0^1^3 -> 2 which is the missing number.
xor = len(nums)
for index in range(len(nums)):
xor = xor ^ index ^ nums[index]
return xor
- Note: I will be adding more useful bit operations as and when I encounter them ๐
=================
The End!
ย