You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
Input : N = 1, M = 2, i = 2, j = 4 Output: 9 N = 00000001(Considering 8 bits only) M = 10 (Binary of 2) For more indexes, leading zeroes will be considered. Now set 3 bits from ith index to j in the N as in the M. Bits:- 0 0 0 (0 1 0) 0 1 = 9 Indexes:- 7 6 5 4 3 2 1 0 From index 2 to 4, bits are set according to the M.
Asked in : Adobe
A simple solution is to traverse all bits in N from 0 to 31 and set the bits equals to M in the range from i to j.
An efficient solution is to do following steps.
- Set all the bits after j in a number.
- Set all the bits before i in a number.
- Then perform Bitwise Or on both then we get the number with all the bits set except from i to j.
- Perform Bitwise And with the given N as to set the bits according to the N.
- Then shift M into the correct position i.e. in the range of i to j.
- And at the last perform Bitwise Or on (Shifted M and the N modifed in 4th step).
- The result will be N with M as substring from ith to jth bits
This article is contributed by Sahil Chhabra. 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.
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Swap all odd and even bits
- Toggle all the bits of a number except k-th bit.
- Copy set bits in a range
- Find even occurring elements in an array of limited range
- Print first n numbers with exactly two set bits
- Check if bits of a number has count of consecutive set bits in increasing order
- Bitwise and (or &) of a range
Improved By : jit_t