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).
publicstaticintupdateBits(int n, int m, int i, int j) {
int max =~0; /* All 1's */// 1's through position j, then 0'sint left = max - ((1<< (j + 1)) - 1); // here should be j+1 not j.// 1's after position iint right = ((1<< i) - 1);
// 1's with 0s between i and jint mask = left | right;
// Clear i through j, then put m in therereturn (n & mask) | (m<< i);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defupdateBits(N, M, i, j):
# Create a mask to clear bits from i to j in N all_ones =~0# Sequence of all 1's# 1's before position j, followed by 0's left = all_ones << (j +1)
# 1's after position i right = (1<< i) -1# All 1's, except for 0's between i and j mask = left | right
# Clear bits j through i then put M in there N_cleared = N & mask
M_shifted = M << i
# OR N_cleared with M_shiftedreturn N_cleared | M_shifted