×

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:

  1. Not ~
  2. AND &
  3. OR |
  4. LEFT SHIFT <<
  5. RIGHT SHIFT >>
  6. 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:

  1. Read N.
  2. Set n= n | n >>1
  3. Set n= n | n >>2
  4. Set n= n | n >>4
  5. Set n= n | n >>8
  6. Set n= n | n >>16
  7. Set n = (( n+1)>>1 | (n & (1 <<((sizeof(n)*CHAR_BIT-1)));
  8. 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.

  1. Read n.
  2. Initialize result= n && (!(n&(n-1)))
  3. 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:

  1. Read Number.
  2. Initialize n= number.
  3. Set n= n | n >>1
  4. Set n= n | n >>2
  5. Set n= n | n >>4
  6. Set n= n | n >>8
  7. Set n= n | n >>16
  8. 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.

  1. Read N
  2. Check the value of :((n+1)&n)
    • if it is equal to 0
      return 1.
    • else
      return 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:

  1. Read N
  2. Set leading_zero = ___builtin_clz(n).
  3. 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.


Related Topics

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

What is the difference between DFS and BFS?

What is BFS? BFS is generally known as the low level traversal. As we already know that it stands for breadth first search and is mainly used in the queue data...

4 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.