Home » C programs » C bitwise operator's programs

# C program to Check if nth Bit in a 32-bit Integer is set or not

In this article, we are going to see **how to find nth bit of a 32-bit integer is set or not using bitwise operator**?

Submitted by Radib Kar, on January 06, 2019

Problem statement: **Write a C program to check if nth bit is set or not in a 32 bit integer.**

**Solution:** Pre-requisite: input no(32 bit longer), nth bit

**Algorithm**

- Right shift by n times to get the nth bit at LSB
- Do a bitwise and with 1(only LSB is set of 1, other bits 0).
- IF result is 1, then nth bit is set

Else

Bit not set

**Example with explanation:**

Let input no be 67600 and n is 11

This is the binary representation of 67600

After right shifting 11 times,

So bitwise ANDing this shifted no with 1

Results in 00000...0001(31 0's & one 1) which is 1... Thus **n th bit is set**...

## C implementation to Check if nth Bit in a 32-bit Integer is set or not

#include <stdio.h> int main() { int n,k; printf("enter a 32 bit number\n"); scanf("%d",&k); printf("enter the bit no to check...\n"); printf("bit-no 0-indexed & 0 starts from LSB...\n"); scanf("%d",&n); if(n>32){ printf("enter between 0-31\n"); return; } k=k>>n; //right shift the no to get nth bit at LSB if(k&1==1) //check whether nth bit set or not printf("%d th bit is set\n",n); else printf("%d th bit not set\n",n); return 0; }

**Output**

First run: enter a 32 bit number 67600 enter the bit no to check... bitno 0-indexed & 0 starts from LSB... 11 11 th bit is set Second run: enter a 32 bit number 67600 enter the bit no to check... bit-no 0-indexed & 0 starts from LSB... 10 10 th bit not set

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.