Bitwise Operators and their Important Tricks
In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task, but to write efficient code and improve your logic, you need to go beyond this.
To perform operations like data encryption or data compression, you need to deal with a deeper level of storage structures. Since Bitwise operators work on the ground level in our system they are faster, they optimize the program to a good level.
Midnight hospitals are faster than normal operators as they deal directly with bit-level data and hence can be used to optimize the time complexity of different programs. Before going to the tricks, let's first brush up on some important concepts of Bitwise operations.
Following are the six widely used Bitwise operators:
- Not ~
- AND &
- OR |
- LEFT SHIFT <<
- RIGHT SHIFT >>
- XOR ^
Bitwise NOT
This is a unary operator used when you need to flip all the bits for a number. In other words, this operator returns the one's complement of a binary number.
For example,
X=2 =(010)2
~x=(101)2 =5
Bitwise AND
This is a binary operator, and as the name depicts, it just returns the output of the AND operation on each and every single bit of the two operands.
If both the bits that are being compared are 1, then only the result is one else; it is zero.
For example,
X=2 =(010)2
Y=5 =(101)2
X AND Y=(000)2 =0
Bitwise OR
This Binary operator just returns the output of or operation performed on each of the bits from on the two inputs.
For example,
X=2 =(010)2
Y=5 =(101)2
X OR Y=(111)2 =7
Bitwise XOR
This Bitwise operator takes two inputs of the same length and compares each of their bits. If both of the bits that are being compared are the same, then the result would be zero; else, it would return 1
For example,
X=2 =(010)2
Y=5 =(101)2
X XOR Y=(111)2 =7
Bitwise LEFT-SHIFT
This binary operator, technically speaking, shifts the n bits from the m number to the left and appends 0 at the end. Basically, it returns the value of m * 2^n, and if the two operands are m and n
For example,
X=1 =(01)2
Y=2 =(10)2
X << Y=(0100)2 =4
Or you can understand this as:
X= 1
Y= 2
X<< Y = 1*22 =4
Bitwise RIGHT-SHIFT
This binary operator, technically speaking this operator shifts the n bits from the m number to the right and appends 1 at the end. It basically returns the value of m / 2^n, where m and n are the two operands.
For example,
X=4 =(0100)2
Y=1
X << Y=(010)2 =2
Or you can understand this as:
X= 4
Y= 1
X>> Y = 4/21 =2
Tricks of Bit-Wise Operators
Now let’s move towards up of the important techniques or tricks that you can use in your programs welding with BITS in your straight should help you to write time-efficient quotes for the operations that you almost use in every algorithm in order to build a good program.
1. Swapping two numbers using Bitwise operators
Algorithm to swap two numbers without using any kind of extra space as well as pointers:
- Read inputs x and y.
- Set x = x ^ y (X XOR Y).
- Set y = y ^ x
- Assign x ^ y to x again.
- Print the swapped results
This is an efficient way to swap two variables in your program.
2. Calculate the XOR of all the numbers from 1 to n
By observing the XOR of all the numbers from 0 to n you would find a common pattern sequence in them.
Using the logic behind this pattern, an efficient algorithm can be designed in such a way that you would be able to find the XOR of all the numbers from 0 to n in constant time complexity.
The algorithm is:
- Read N.
- Calculate N%4.
- Set I =N%4.
- Check the value of I:
a) For I==0
Print N.
b) For I==1
Print N.
c) For I==2
Print N+1.
d) For I==3
Print 0.
This efficient way prints the XOR of 1 to n numbers in O(1) time complexity, whereas a normal algorithm with a naive approach would take O(N) time for the same.
Using bit operators, find a number's MSB (Most Significant Bit) efficiently
The most efficient way to find the most significant bit of a fixed-size interior would be to use an algorithm that should directly deal with the bits.
The algorithm to find the MSB would be:
- Read N.
- Set n= n | n >>1
- Set n= n | n >>2
- Set n= n | n >>4
- Set n= n | n >>8
- Set n= n | n >>16
- Set n = (( n+1)>>1 | (n & (1 <<((sizeof(n)*CHAR_BIT-1)));
- Return N.
This algorithm can find the most significant bit of a number in just O(1) time complexity.
Check if a number is a power of two.
You can directly use this trick to find whether a number is a power of two or not.
- Read n.
- Initialize result= n && (!(n&(n-1)))
- Return result.
Directly return TRUE OR FALSE in constant time and can help you to save a lot of time in many programs.
Convert a given binary number to an integer
The auto keyword in c is used for this task and returns the desired value
For example,
int main(){
auto value= 0b0110010
printf("%d", value);
}
Flipping all bits of a number
When you need to flip all the bits of a number, you can easily do the same by subtracting it from any number in which all the bits are set.
For example,
Number= 0011010
The number in which all the bits are set = 111111
Subtraction= 1100101 (numbers with flipped bits)
Algorithm:
- Read Number.
- Initialize n= number.
- Set n= n | n >>1
- Set n= n | n >>2
- Set n= n | n >>4
- Set n= n | n >>8
- Set n= n | n >>16
- Return (n - number).
Like this, you could get the number with all the flipped bits in constant time.
Check if the sequence of bits of any number has an alternate pattern.
Whenever you need to find any pattern in a sequence of bits, you can use the Bitwise XOR operation to check whether there is an alternate pattern.
The below algorithm can be used for the same.
- Read N
- Check the value of :((n+1)&n)
- if it is equal to 0
return 1. - else
return 0.
- if it is equal to 0
This algorithm is a helpful trick you can use whenever you need to find any number with a specific type of bits sequence.
Finding the number of leading and trailing zeros in any number
You can directly use the inbuilt GCC function to find the number of leading and trailing zeros of any number.
For example:
- Read N
- Set leading_zero = ___builtin_clz(n).
- return leading_zero.
These are some useful Bitwise manipulation tricks you can use in your various programs to reduce their time complexity and hence write efficient codes.