Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Check whether the bit at given position is set or unset

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two positive integers n and k. The problem is to check whether the bit at position k from the right in the binary representation of n is set (‘1’) or unset (‘0’). 
Constraints: 1 <= k <= number of bits in the binary representation of n.
Examples: 
 

Input : n = 10, k = 2
Output : Set
(10)10 = (1010)2
The 2nd bit from the right is set.

Input : n = 21, k = 4
Output : Unset

 

Approach#1: Following are the steps:
 

  1. Calculate new_num = (n >> (k – 1)).
  2. if (new_num & 1) == 1 then bit is “Set”, else “Unset”.

 

C++




// C++ implementation to check whether the bit
// at given position is set or unset
#include <bits/stdc++.h>
using namespace std;
 
// function to check whether the bit
// at given position is set or unset
bool bitAtGivenPosSetOrUnset(unsigned int n,
                             unsigned int k)
{
    int new_num = n >> (k - 1);
 
    // if it results to '1' then bit is set,
    // else it results to '0' bit is unset
    return (new_num & 1);
}
 
// Driver program to test above code
int main()
{
    unsigned int n = 10, k = 2;
    if (bitAtGivenPosSetOrUnset(n, k))
        cout << "Set";
    else
        cout << "Unset";
    return 0;
}


Java




// Java program to
// check the set bit
// at kth position
import java.io.*;
 
class GFG {
     
// function to check whether
// the bit at given position
// is set or unset
static int bitAtGivenPosSetOrUnset
                   ( int n, int k)
{
 
    // to shift the kth bit
    // at 1st position
    int new_num = n >> (k - 1);
  
    // Since, last bit is now
    // kth bit, so doing AND with 1
    // will give result.
    return (new_num & 1);
}
    public static void main (String[] args)
    {
         // K and n must be greater than 0
         int n = 10, k = 2;
          
    if (bitAtGivenPosSetOrUnset(n, k)==1)
        System.out.println("Set");
    else
        System.out.println("Unset");
    }
}
 
//This code is contributed by Gitanjali


Python3




# python implementation to check
# whether the bit at given
# position is set or unset
 
import math
#function to check whether the bit
# at given position is set or unset
def bitAtGivenPosSetOrUnset(  n,  k):
     new_num = n >> (k - 1)
  
     #if it results to '1' then bit is set,
     #else it results to '0' bit is unset
     return (new_num & 1)
 
# Driver code
n = 10
k = 2
if (bitAtGivenPosSetOrUnset(n, k)):
     print("Set")
else:
    print("Unset")
 
#This code is contributed by Gitanjali


C#




// C# program to check the set bit
// at kth position
using System;
 
class GFG {
     
    // function to check whether
    // the bit at given position
    // is set or unset
    static int bitAtGivenPosSetOrUnset(
                           int n, int k)
    {
     
        // to shift the kth bit
        // at 1st position
        int new_num = n >> (k - 1);
     
        // Since, last bit is now
        // kth bit, so doing AND with 1
        // will give result.
        return (new_num & 1);
    }
     
    // Driver code
    public static void Main ()
    {
         
        // K and n must be greater
        // than 0
        int n = 10, k = 2;
         
        if (bitAtGivenPosSetOrUnset(n, k)==1)
            Console.Write("Set");
        else
            Console.Write("Unset");
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP implementation to check whether the bit
// at given position is set or unset
 
// function to check whether the bit
// at given position is set or unset
function bitAtGivenPosSetOrUnset($n, $k)
{
    $new_num = $n >> ($k - 1);
 
    // if it results to '1' then bit is set,
    // else it results to '0' bit is unset
    return ($new_num & 1);
}
 
    // Driver Code
    $n = 10;
    $k = 2;
    if (bitAtGivenPosSetOrUnset($n, $k))
        echo "Set";
    else
        echo "Unset";
         
// This code is contributed by Sam007
?>


Javascript




<script>
 
// javascript program to
// check the set bit
// at kth position
 
// function to check whether
// the bit at given position
// is set or unset
function bitAtGivenPosSetOrUnset
                   (n, k)
{
   
    // to shift the kth bit
    // at 1st position
    let new_num = n >> (k - 1);
    
    // Since, last bit is now
    // kth bit, so doing AND with 1
    // will give result.
    return (new_num & 1);
}
 
// Driver Function
 
         // K and n must be greater than 0
         let n = 10, k = 2;
            
    if (bitAtGivenPosSetOrUnset(n, k)==1)
        document.write("Set");
    else
        document.write("Unset");
     
    // This code is contributed by susmitakundugoaldanga.
</script>


Output: 
 

Set

Time Complexity: O(1)

Auxiliary Space: O(1)

Approach#2: We can use the left shift to solve this problem. Following are the steps:

  • New_num = ( 1 << ( k – 1 ) )
  • If ( num & New_num ) == 1 then bit is set else unset. 

C++




// C++ implementation to check whether the bit
// at given position is set or unset
// Using left shift operator
#include <bits/stdc++.h>
using namespace std;
 
// function Using left shift operator
bool bitAtGivenPosSetOrUnset(unsigned int n,
                             unsigned int k)
{
    int New_num = 1 << (k - 1);
 
// Returning result
    return (New_num & n);
}
 
// Driver program to test above code
int main()
{
    unsigned int n = 10, k = 2;
    if (bitAtGivenPosSetOrUnset(n, k))
        cout << "Set";
    else
        cout << "Unset";
    return 0;
}


Java




// Java program to
// check the set bit
// at kth position
import java.io.*;
 
class GFG {
     
// function to check whether
// the bit at given position
// is set or unset
static int bitAtGivenPosSetOrUnset
                   ( int n, int k)
{
 
    // to shift the kth bit
    // at 1st position
    int New_num = 1 << (k - 1);
  
    // Since, last bit is now
    // kth bit, so doing AND with 1
    // will give result.
    return (New_num & n);
}
    public static void main (String[] args)
    {
         // K and n must be greater than 0
         int n = 10, k = 2;
          
    if (bitAtGivenPosSetOrUnset(n, k)==k)
        System.out.println("Set");
    else
        System.out.println("Unset");
    }
}
 
//This code is contributed by sam snehil


Python3




# python implementation to check
# whether the bit at given
# position is set or unset
# by Using left shift operator
 
import math
#function to check whether the bit
# at given position is set or unset
# by Using left shift operator
def bitAtGivenPosSetOrUnset(  n,  k):
     New_num = 1 << (k - 1)
      
     # returning result
     return (New_num & n)
 
# Driver code
n = 10
k = 2
if (bitAtGivenPosSetOrUnset(n, k)):
     print("Set")
else:
    print("Unset")
 
#This code is contributed by sam snehil


C#




// C# program to check the set bit
// at kth position Using left shift operator
using System;
 
class GFG {
    // Function using left shift operator
    static int bitAtGivenPosSetOrUnset(
                           int n, int k)
    {
     
        int New_num = 1 << (k - 1);
     
        // Returning result
        return (New_num & n);
    }
     
    // Driver code
    public static void Main ()
    {
         
        int n = 10, k = 2;
         
        if (bitAtGivenPosSetOrUnset(n, k) != 0)
            Console.Write("Set");
        else
            Console.Write("Unset");
    }
}
 
// This code is contributed by Sam snehil.


Javascript




// javascript program to check set bit using left shift operator
 
// function using left shift operator
function bitAtGivenPosSetOrUnset
                   (n, k)
{
   
    let New_num = 1 << (k -1);
    
    // Returning result
    return (New_num & n);
}
 
// Driver Function
// K and n must be greater than 0
     let n = 10, k = 2;
            
    if (bitAtGivenPosSetOrUnset(n, k))
        console.log("Set");
    else
        console.log('Unset')
     
    // This code is contributed by sam snehil.


PHP




<?php
// PHP implementation to check whether the bit
// at given position is set or unset Using left shift operator
 
// function demonstrate left shift operator working
function bitAtGivenPosSetOrUnset($n, $k)
{
    $New_num = 1 << ($k - 1);
 
    return ($New_num & $n);
}
 
    // Driver Code
    $n = 10;
    $k = 2;
    if (bitAtGivenPosSetOrUnset($n, $k))
        echo "Set";
    else
        echo "Unset";
         
// This code is contributed by Sam snehil
?>


Output:

Set

Time Complexity: O(1)

Auxiliary Space: O(1)

Approach#3: We can use power of 2 to check if the Bitwise AND of ‘(k-1)th power of 2’ and num is 1 or not. If it is 1 , the bit is set else unset.

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the kth bit is set
// or not in num
bool bitAtGivenPosSetOrUnset(int n, int k)
{
    int new_num = pow(2,(k -1));
    int x=new_num & n;//storing bitwise AND
   
    if(x > 0)
    { return true;// return true if kth bit is set
    }
    else{
    return false; // else return false
  }
}
// Drive Code
int main()
{
    int n = 10, k = 2;
   
    // Function call
    if (bitAtGivenPosSetOrUnset(n, k))
        cout << "Set";
    else
        cout << "Unset";
    return 0;
}
 
// This code is contributed by nikhilsainiofficial546


Java




import java.lang.Math;
 
public class Main {
 
  // Function to check if the kth bit is set
  // or not in num
  static boolean bitAtGivenPosSetOrUnset(int n, int k)
  {
    int new_num = (int) Math.pow(2, k - 1);
    int x = new_num & n;  // storing bitwise AND
 
    if (x > 0) {
      return true// return true if kth bit is set
    }
    else {
      return false// else return false
    }
  }
 
  // Driver Code
  public static void main(String[] args) {
    int n = 10, k = 2;
 
    // Function call
    if (bitAtGivenPosSetOrUnset(n, k))
      System.out.println("Set");
    else
      System.out.println("Unset");
  }
}


Python3




# Python3 implementation of the above approach
 
# Function to check if the kth bit is set or not in n
def bitAtGivenPosSetOrUnset(n, k):
     
    new_num = pow(2, k-1)
     
    # Check if the kth bit is set or not by performing bitwise AND
    x = new_num & n
     
    # Return True if kth bit is set, else False
    if x > 0:
        return True
    else:
        return False
       
 
# Drive Code
n = 10
k = 2
 
# Function call
if bitAtGivenPosSetOrUnset(n, k):
    print("Set")
else:
    print("Unset")
 
  # This code is contributed by nikhilsainiofficial546


C#




using System;
 
public class Program
{
    // Function to check if the kth bit is set
// or not in num
public static bool bitAtGivenPosSetOrUnset(int n, int k)
{
    int new_num = (int)Math.Pow(2, (k - 1));
    int x = new_num & n;//storing bitwise AND
 
    if (x > 0)
    {
        return true;// return true if kth bit is set
    }
    else
    {
        return false; // else return false
    }
}
    // Drive Code
    public static void Main()
    {
        int n = 10, k = 2;
        // Function call
        if (bitAtGivenPosSetOrUnset(n, k))
            Console.WriteLine("Set");
        else
            Console.WriteLine("Unset");
    }
}
//This code is contributed by NarasingaNikhil


Javascript




// Javascript implementation of the above approach
 
// Function to check if the kth bit is set or not in num
function bitAtGivenPosSetOrUnset(n, k) {
  const new_num = Math.pow(2, k - 1);
  const x = new_num & n; // storing bitwise AND
 
  if (x > 0) {
    return true; // return true if kth bit is set
  } else {
    return false; // else return false
  }
}
 
// Drive Code
const n = 10, k = 2;
 
// Function call
if (bitAtGivenPosSetOrUnset(n, k)) {
  console.log("Set");
} else {
  console.log("Unset");
}


Output

Set

Time Complexity: O(1) 
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Last Updated : 07 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials