I've been trying to work through the first problem in CTCI, which involves bit manipulation, and I just can't figure out how the author accurately made the mask in his final solution. Could someone explain the calculations for "int left", "int right", and "int mask"? It would be great to see what these lines are calculating specifically for the example he provided.
The Question is: 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). EXAMPLE: Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100
public static int updateBits(int n, int m, int i, int j) {
int max = ~0; /* All 1’s */
// 1’s through position j, then 0’s
int left = max - ((1 << j) - 1);
// 1’s after position i
int right = ((1 << i) - 1);
// 1’s, with 0s between i and j
int mask = left | right;
// Clear i through j, then put m in there
return (n & mask) | (m << i);
}
(1 << j)
has just the bit at positionj
set to1
((1 << j) - 1)
(subtracting1
) yields allj
bits below (to the right of) positionj
set to1
max - ((1 << j) - 1)
(subtracting from all 1) yields the bitwise complement of the above, i. e. all bits above (to the left of) and including positionj
set to1
, and thej
bits below set to0
e. g.
(1 << i)
has just the bit at positioni
set to1
((1 << i) - 1)
(subtracting1
) yields alli
bits below (to the right of) positioni
set to1
e. g.
i = 2, j = 6:
(n & mask)
, unlike commented, clears bitsi
throughj
-1 only (seemask
above)(m << i)
shifts the value to be set to the desired bit position(n & mask) | (m << i)
ORs the shifted value bits to the maskedn
with your example:
Now, although this example values yield a correct result, we can see that the implementation of
updateBits()
is actually wrong, because theleft
part of themask
needs1
bits only to the left of and not including positionj
, since bit positionj
belongs to the substring that is to be masked out. The wrongness shows e. g. with the values n = 11111111111, m = 00000, i = 2, j = 6:The value m has been put into bit positions i to j-1 only.
The error can be corrected by changing
to