Find, Set, Clear, Toggle and Modify bits in C
Given a positive integer N, the task is to perform the following sequence of operations on the binary representation of N in C.
Examples:
Input:N = 5, K = 1, P = 0 Output: K(= 1)th bit of 5 is 1. Setting the K(= 1)th bit modifies N to 5 Clearing the K(= 1)th bit modifies N to 4. Toggling the K(= 1)th bit modifies N to 4. Replacing the K(= 1)th bit with P(= 0) modifies N to 4
Input: N = 10, K = 2, P = 1 Output: Kth(= 2) bit of 5 is 1. Setting the K(= 2)th bit modifies N to 10. Clearing the K(= 2)th bit modifies N to 8. Toggling the K(= 2)th bit modifies N to 8. Replacing the K(= 2)th bit with P(= 1) modifies N to 10.
Approach: Follow the steps below to find, set, clear, toggle and modify the Kth bit in the binary representation of N.
Finding a bit:
(N >> K) & 1
Setting a bit:
N = N | (1 << K)
Clearing a bit:
N = N & ~(1 << K)
Toggle a bit:
N = N ^ (1 << K)
Modify a bit:
N = N | (P << K)
Below is the implementation of the above approach:
C
#include <stdio.h>
int setBit( int n, int k)
{
return (n | (1 << (k - 1)));
}
int clearBit( int n, int k)
{
return (n & (~(1 << (k - 1))));
}
int toggleBit( int n, int k)
{
return (n ^ (1 << (k - 1)));
}
int modifyBit( int n, int k, int p)
{
return (n | (p << k));
}
int findBit( int n, int k)
{
return ((n >> k) & 1);
}
void bitOperations( int n, int k,
int p)
{
printf ( "K(= %d)-th bit of %d is %d\n" ,
k, n, findBit(n, k));
printf ( "Setting K(= %d)th bit modifies N to %d\n" ,
k, setBit(n, k));
printf ( "Clearing K(= %d)th bit modifies N to %d\n" ,
k, clearBit(n, k));
printf ( "Toggling K(= %d)th bit modifies N to %d\n" ,
k, toggleBit(n, k));
printf ( "Replacing the K(= %d)<sup>th</sup> bit" , k);
printf ( " with P(= %d) modifies N to 10\n" ,
modifyBit(n, k, p));
}
int main()
{
int n = 5, k = 1, p = 1;
bitOperations(n, k, p);
return 0;
}
|
Output
K(= 1)-th bit of 5 is 0
Setting K(= 1)th bit modifies N to 5
Clearing K(= 1)th bit modifies N to 4
Toggling K(= 1)th bit modifies N to 4
Replacing the K(= 1)th bit with P(= 7) modifies N to 10
Time Complexity: O(log(N))Auxiliary Space: O(1)
Last Updated :
07 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...