You are given two 32-bit numbers, N and M, and two bit positions, i and j Write amethod to set all bits between i and j in N equal to M (e g , M becomes a substring ofN located at i and starting at j)
EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6Output: N = 10001010100
===========
Analysis:
Step 1, set bits between i and j to 0 in n.
Step 2, m left shift i.
Step 3, n&m.
public static int updateBits(int n, int m, int i, int j){
int allOne = ~0;
int left = allOne<<j+1; // left to right, all 1 till position j+1, then all 0
int right = (1<<i)-1; // right to left, all 1 till position i-1, then all 0
int mask = left|right; // 0 from position i to position j, others all 1
return (n&mask)|(m<<i);
}
public static void main(String[] args) {
int a = 103217;
System.out.println(AssortedMethods.toFullBinaryString(a));
int b = 13;
System.out.println(AssortedMethods.toFullBinaryString(b));
int c = updateBits(a, b, 4, 7);
System.out.println(AssortedMethods.toFullBinaryString(c));
}