Given a number n, a position p and a binary value b, we need to change the bit at position p in n to value b.
Input : n = 7, p = 2, b = 0 Output : 3 7 is 00000111 after clearing bit at 2rd position, it becomes 0000011. Input : n = 7, p = 3, b = 1 Output : 15 7 is 00000111 after setting bit at 3rd position it becomes 00001111.
We first create a mask that has set bit only at given position using bit wise shift. mask = 1 << position Then to change value of bit to b, we first make it 0 using below operation value & ~mask After changing it 0, we change it to b by doing or of above expression with following (b << p) & mask, i.e., we return (n & ~mask) | ((b << p) & mask)
Below is the implementation of above steps :
Time Complexity :O(1)
This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Modify a binary array to Bitwise AND of all elements as 1
- Modify array by merging elements with addition such that it consists of only Primes.
- Position of the K-th set bit in a number
- Position of rightmost set bit
- Find position of the only set bit
- Position of rightmost different bit
- Check whether the bit at given position is set or unset
- Get the position of rightmost unset bit
- Find the value at kth position in the generated array
- Position of rightmost bit with first carry in sum of two binary
- Position of rightmost common bit in two numbers
- Extract 'k' bits from a given position in a number.
- Check whether the two numbers differ at one bit position only
- Python Slicing | Extract ‘k’ bits from a given position
- Find position of left most dis-similar bit for two numbers
- Find letter's position in Alphabet using Bit operation
- Find position of given term in a series formed with only digits 4 and 7 allowed