Bit manipulation, in some cases, can obviate or reduce the need to loop over a data structure and can give many-fold speed-ups, as bit manipulations are processed in parallel, but the code can become more difficult to write and maintain.
1.Check the integer is even or odd.
def even_or_odd(num):
if (num & 1) == 0:
return f"{num} is even number"
else:
return f"{num} is odd number"
2.Multiply by 2 using the left shift operator:
print(7 << 1)
output: 14
3.Divide 2 using the right shift operator:
print(14 >> 1)
output: 7
4.One’s complement operator (~): If we want to invert every bit of a number i.e change bit ‘0’ to ‘1’ and bit ‘1’ to ‘0’.
num = 7
print(~num)
output: -8
5.Two’s complement of the number:
num = 5
twos_complement = -num
print(f"This is two's complement {twos_complement}")
print(f"This is also two's complement {~num + 1}")
6.Upper case English alphabet to lower case: ch |= ' '
This mask is bit representation of space character (‘ ‘).
ch = ‘A’ #(01000001)
mask = ‘ ‘ #(00100000)
ch | mask = ‘a’ #(01100001)
7.Lower case English alphabet to upper case: ch &= '’
This mask is a bit representation of the underscore character (‘‘). The character ‘ch’ then AND with mask.
ch = ‘a’ #(01100001)
mask = ‘_ ‘ #(11011111)
ch & mask = ‘A’ #(01000001)
8.A number is a power of 2.
x and (not(x & (x - 1)))
9.The Quickest way to swap two numbers.
a = a ^ b
10.Count set bits in an integer.
def countSetBits(n):
count = 0
while (n):
count += n & 1
n >>= 1
return count
Maybe you can use bin() function.
print(bin(15).count('1'))
# output 4
Brian Kernighan’s Algorithm: If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit count.
def countSetBits(n):
count = 0
while (n):
n &= (n-1)
count += 1
return count
11.Count unset bits of a number.
def countunsetbits(n):
count = 0
x = 1
while(x < n + 1):
if ((x & n) == 0):
count += 1
x = x << 1
return count
Toggle all bits after the most significant bit
def toggle(n):
temp = 1
while (temp <= n):
n = n ^ temp
temp = temp << 1
return n