Check whether the bit at given position is set or unset

23 Jun, 2022
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
 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Approach#1: Following are the steps: 
Calculate new_num = (n >> (k – 1)).if (new_num & 1) == 1 then bit is “Set”, else “Unset”.
Calculate new_num = (n >> (k – 1)).
if (new_num & 1) == 1 then bit is “Set”, else “Unset”.
 
C++
Java
Python3
C#
PHP
Javascript
// 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 unsetbool 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 aboveint main(){    unsigned int n = 10, k = 2;    if (bitAtGivenPosSetOrUnset(n, k))        cout << "Set";    else        cout << "Unset";    return 0;}
// Java program to// check the set bit// at kth positionimport java.io.*; class GFG {     // function to check whether// the bit at given position// is set or unsetstatic 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
# 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 unsetdef 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 coden = 10k = 2if (bitAtGivenPosSetOrUnset(n, k)):     print("Set")else:    print("Unset") #This code is contributed by Gitanjali
// C# program to check the set bit// at kth positionusing 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 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 unsetfunction 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?>
<script> // javascript program to// check the set bit// at kth position // function to check whether// the bit at given position// is set or unsetfunction 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). 
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++
Javascript
Python3
C#
PHP
Java
// 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 operatorbool bitAtGivenPosSetOrUnset(unsigned int n,                             unsigned int k){    int New_num = 1 << (k - 1); // Returning result    return (New_num & n);} // Driver program to test aboveint main(){    unsigned int n = 10, k = 2;    if (bitAtGivenPosSetOrUnset(n, k))        cout << "Set";    else        cout << "Unset";    return 0;}
// javascript program to check set bit using left shift operator // function using left shift operatorfunction 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.
# 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 operatordef bitAtGivenPosSetOrUnset(  n,  k):     New_num = 1 << (k - 1)           # returning result     return (New_num & n) # Driver coden = 10k = 2if (bitAtGivenPosSetOrUnset(n, k)):     print("Set")else:    print("Unset") #This code is contributed by sam snehil
// C# program to check the set bit// at kth position Using left shift operatorusing 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.
<?php// PHP implementation to check whether the bit// at given position is set or unset Using left shift operator // function demonstrate left shif operator workingfunction 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?>
// Java program to// check the set bit// at kth positionimport java.io.*; class GFG {     // function to check whether// the bit at given position// is set or unsetstatic 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
Output:
Set
Check whether the bit at given position is set or unset | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersCheck whether the bit at given position is set or unset | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9h9pnVwv_vk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
Sam007
susmitakundugoaldanga
satyam00so
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.