2011-03-31 71 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