×

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

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

4 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java In this article, we are going to see how to find the intersection point in a Y-shaped linked list. Method 1: We need to...

4 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Deletion in Binary Search Tree

Implementation #include <iostream> using namespace std; struct _nod {   int ky;   struct _nod *Lft, *Rt; }; // Creating a node in the binary tree. struct _nod *nw_nod(int Itm) {   struct _nod *temp = (struct _nod *)malloc(sizeof(struct...

4 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Binary Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

8 minutes read.