Check whether kth bit is set or not in C++

Hello, friends in this tutorial we will write a program to check the kth bit of a number is set or in C++.

We have a number say N we will check if the kth bit of the number is set or not.

We will use two methods to check

  1. By using left shift operator
  2. By using the right shift operator

For example, we have number N=3 and k=1 i.e check if the first bit is set or not so we know that the binary representation of 3 is “11” the first bit is 1 i.e it is set so our output will be “YES”.

Let us now consider N=5 and K=2 i.e check if the second bit is set or not so the binary of 5 is “101” the second bit is 0 so our output will be “NO”.

C++ program to check the kth bit is set or not

We will be doing this using the below operators:

  • Right shift operator
  • Left shift operator

Using Right Shift Operator

We right shift number N by k-1 position and perform bitwise & with 1 so check if the last bit is 1 or not if last bit is 1 then the kth bit is set else if the bit is 0 it is not set.

Following is the code to check the kth bit using right shift operation.

#include<iostream>
using namespace std;

int main()
{
  int num = 5;
  int k = 1;
  

  if ((num >> (k - 1)) && 1 )
      cout<<"Bit is SET";
  else
      cout<<"Bit is not SET";
  return 0;
}

 

OUTPUT:

Bit is SET

 

Using Left Shift Operator

We left shift 1 by k-1 position and perform bitwise & with N to check it the last bit is set or not if the last bit is 1 then the kth bit is set else if the bit is 0 it is not set.

Following is the code to check the kth bit using left shift operation

#include<iostream>
using namespace std;

int main()
{
  int num = 5;
  int k = 1;
  

  if ((1 << (k - 1)) && num )
      cout<<"Bit is SET";
  else
      cout<<"Bit is not SET";
  return 0;
}

 

OUTPUT:

Bit is SET

Leave a Reply

Your email address will not be published. Required fields are marked *