given two 32bit numbers, n and m, and two bit positions, i and j. write a method to insert M into N such that M starts at bit j and ends at bit i. you can assume that the bits j t hrough i have enough space to fit all of M/
input N = 100 0000 0000 M = 10011, i = 2, j = 6
output N = 100 0100 1100
int setMask(int i, int j){
int len = j-i+1;
int result = 1;
while(len>1){
result = (result<<1)+1;
len--;
}
while(i>0){
result = result << 1;
i--;
}
return result;
}
int setBit(int n, int m, int i, int j){
if (i>j){
cout<<"Error: i>j" <<endl;
return 0;
}
if (i<0 || j>31){
cout<<"Error: i,j range is wrong" <<endl;
return 0;
}
int tempm = m;
int lenm = 0;
while(tempm){
tempm= tempm >> 1;
lenm++;
}
if (j-i+1>lenm)
j = i+lenm-1;
int mask = setMask(i,j);
n &= ~mask;
while(i>0){
m = m<<1;
i--;
}
n |= m;
}
1. 注意边界检查
2. 这个set mask的方法太复杂了,自己都看不下去了……
int allones = ~0;
int left = allones<<(j+1);
int right = (1<<i)-1;
int mask = left|right;
3. 原来写的 m<<1, 这样是错的,这样并不能改变m的值,应该改为m <<=1