Set, Clear and Toggle a Given Bit of a Number in C
Last Updated :
12 Jul, 2025
Write a C program to Set, Clear, and Toggle the given bit of a number.
- Setting a bit means that if Kth bit is 0, then set it to 1 and if it is 1 then leave it unchanged.
- Clearing a bit means that if Kth bit is 1, then clear it to 0 and if it is 0 then leave it unchanged.
- Toggling a bit means that if Kth bit is 1, then change it to 0 and if it is 0 then change it to 1.
Examples:
Input: N = 5, K = 1
Output: Setting Kth bit: 5
Clearing Kth bit: 4
Toggling Kth bit: 4
Explanation: 5 is represented as 101 in binary and has its first bit 1, so
Setting it will result in 101 i.e. 5.
Clearing it will result in 100 i.e. 4.
Toggling it will result in 100 i.e. 4.
Input: N = 7, K = 2
Output: Setting Kth bit: 7
Clearing Kth bit: 5
Toggling Kth bit: 5
Explanation: 7 is represented as 111 in binary and has its second bit 1, so
setting it will result in 111 i.e. 7.
clearing it will result in 101 i.e. 5.
toggling it will result in 101 i.e. 5.
To set a specific bit in a number, you have to perform the Bitwise OR operation on the given number with a bit mask in which only the bit you want to set is set to 1, and all other bits are set to 0.
Input: N = 01100111, K = 5
Output: N = 01100111, mask_used: 00100000
We can create the bitmask using the left shift operator and then perform the Bitwise OR operation.
N = N | 1 << K
or
N |= 1 << K
where K is the position of the bit that is to be set, and N is the number.
To clear a specific bit in a number, you have to perform the Bitwise AND operation on the given number with a bit mask in which only the bit you want to clear is set to 0, and all other bits are set to 1.
Input: N = 01100111, K = 5
Output: N = 01100111, mask_used = 1011111
We can create the bitmask using the left shift operator along with NOT operator and then perform the Bitwise AND operation.
N = N & ~ (1 << K)
or
N &= ~ (1 << K)
where K is the position of the bit that is to be set and N is the number.
To toggle a specific bit in a number, you have to perform the Bitwise XOR operation on the given number with a bit mask in which only the bit you want to toggle is set to 1, and all other bits are set to 0.
Input: N = 01100111, K = 5
Output: N = 01100111, mask_used: 00010000
We can create the bitmask using the left shift operator and then perform the Bitwise XOR operation.
N = N ^ 1 << K
or
N ^= 1 << K
where K is the position of the bit that is to be set and N is the number.
C Program to Set, Clear and Toggle a Bit of the Given Number
C
// C program to set, clear and toggle a bit of the given number
#include <stdio.h>
int setBit(int N, int K) {
// Bitwise OR with the mask
return (N | (1 << (K - 1)));
}
int clearBit(int N, int K) {
// Bitwise AND with the mask
return (N & (~(1 << (K - 1))));
}
int toggleBit(int N, int K) {
// Bitwise XOR with the mask
return (N ^ (1 << (K - 1)));
}
int main() {
int N = 5, K = 1;
printf("Original Number: %d, Bit Position: %d\n", N, K);
// Performing the operations
printf("%d with %d-th bit Set: %d\n", N, K, setBit(N, K));
printf("%d with %d-th bit Cleared: %d\n", N, K, clearBit(N, K));
printf("%d with %d-th bit Toggled: %d\n", N, K, toggleBit(N, K));
return 0;
}
OutputOriginal Number: 5, Bit Position: 1
5 with 1-th bit Set: 5
5 with 1-th bit Cleared: 4
5 with 1-th bit Toggled: 4
Time Complexity: O(1), all the operations will have constant time complexity.
Auxiliary Space: O(1)
Conclusion
Setting, clearing, and toggling specific bits in a number are fundamental operations that can be efficiently performed using bitwise operators in C. These operations are often used in low-level programming, where direct manipulation of individual bits is required, such as in embedded systems, memory management, and cryptography.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem