2011-03-31 155 views
0

两个32位数字给出M和N.两个比特位置给出i和j。该方法应该设置i和j之间的所有比特在N中等于M.位操作:修改32位整数以包含子串

N =千万 M = 1111 I = 3且j = 7 输出:N = 10111100

int modifybits(int i,int j,int N,int M) 
    { 

    int max=1; 
    //the string from the left of i and right of j should remain the same and the rest should become 0 
    int left= N>>31-i 
    left=left<<31 

    int right =N<<j 
    right=right>>31-j 

    int new_N=left|right 
    int result=new_N|M 
    print(result) 

    } 

你能提供更好的解决方案,这似乎没有在工作!!日Thnx adv

+3

如果'j - i!= M'的长度会发生什么? – Jon 2011-03-31 09:46:49

+1

这不是真的有助于调用一个整数字符串。 – 2011-03-31 09:54:30

回答

3
int modifybits(int i, int j, int N, int M) { 
     int mask = ~0; // mask with only 1 
     int res = 0; 

     // Note: We need the -1 here because you started numbering bits at 
     // the last position with 1 not with 0 as usual 
     mask = mask >> (i - 1); 
     mask = mask << (i - 1 + 32 - j - 1); 
     mask = mask >> (32 - j - 1); // now mask should contain only 1 at the positions 
           // we want to change in N 

     M = M & mask; // M is now only set at the masked bits 
     N = N & (~mask); //we set all within mask to zero 
     N = N | M; 

     return N; 
} 

另一个说明:我在这里假设32位是系统中整数的大小!否则,你应该在面具的计算中取代32位

+0

运算符优先级不明确。你可以在掩码操作表达式中添加括号吗? – 2011-03-31 10:04:52

+0

完成。谢谢;)我也改变了掩码的定义,所以它有点更通用 – Chris 2011-03-31 10:11:39

2

你的问题不是100%清楚。 “该方法应该设置i和j之间的所有比特在N中等于M” - 但M通常比(j-i)有更多的比特,你是否想要使用相同的位置或位置0 ..(j-i)?另外,在你的例子中,你使用索引1作为LSB(最右边的位)?

你可以使用位域来做到这一点。在你的例子中,你想替换位2-6(?),所以使用位域B = 01111100.

如果你想设置N [2-6]为M [2-6],使用N = (N &〜B)| (M & B)。

如果要将N [2-6]设置为M [0-4],请使用N =(N & B)| ((M < < 2)& B)。

+0

true ...................... – VCODE 2015-01-07 09:46:54