2012-09-13 34 views
2

所以我想解決這個問題:交換位

您將獲得隨機的32位正整數,你所要做的是交換位的值上與第24,25和26位的第3,第4和第5位。

+0

假設你真的被困在一開始。您需要的工具:按位AND('&'),按位OR('|'),左移('<<')和右移('>>')。除此之外,發佈您嘗試過的功能無效。 –

+1

這不是真正意義上的家庭作業,我正在自我教育自己,並問Q我不能回答自己。我很清楚我需要使用按位運算符,但在這種情況下我只是看不到解決方案,所以我決定尋求幫助。 – Leron

+0

感謝您澄清,這不是「家庭作業」。你能至少發表你的想法是關於如何解決它的嗎?如果你解釋這也是爲了自我教育,人們就不會那麼快地假設。 – Oded

回答

6

假設這是你不想要一個明確的解決方案的問題,這裏是一個暗示:屏蔽位問題使用&,做一個轉變,然後OR然後在使用逐|

使用0x00000034掩碼可以「刪除」位3,4和5,使用0x07000000掩碼可以「刪除」位24,25和26。

看看這solution位反轉問題的靈感。

編輯:(響應「沒有一門功課」的評論),因爲這不是一門功課,這裏是一個更深入的解釋:

unsigned int val = ... // your value 
unsigned int bits_03_04_05 = val & 0x00000034; 
unsigned int bits_24_25_26 = val & 0x07000000; 
// Cut out "holes" at bits 3, 4, 5, 24, 25, and 26 of the original value 
unsigned int res = val & ~(0x00000034 | 0x07000000); 
// Put bits 3, 4, and 5 in place 
res |= bits_03_04_05 << 21; 
// Put bits 23, 24, and 25 in place 
res |= bits_24_25_26 >> 21; 
+0

謝謝,會需要時間來完全理解你的解決方案,但我認爲這是我需要什麼來繼續。謝謝。 – Leron

+0

@Leron這可能是值得一提的是這個答案開始計數與位置0位,而馬克Gravell的答案始於1位+1 –

5

如何:

// snag the values from 3,4,5 (small) and 24,25,26 (large) 
    int small = value & (7 << 2), large = value & (7 << 23); 

    // remove the old values, and add in the new ones 
    value = (value^(small | large)) | (large >> 21) | (small << 21); 

(將第1位作爲LSB計數;如果您的意思是第0位是LSB,則將數字調整爲1)

+0

很可愛的要數!特別是「XOR」清除「詭計」。既然你清除了這些位,最後一個'^'可以用'|'替換,對吧? – dasblinkenlight

+0

@dasblinkenlight嗯,是的,我猜是的! –

0

要解決此問題,請使用bi的屬性通過在初始整數值和mask之間應用它們,分別爲operator&operator|

假設你有一個初始值:

unsigned int val;// your value 

你需要形成一個面具:

int setLSB = 1; // 00000001 

int atPosition = 4; 

// shift the set bit 4 positions to the left 
int mask = setLSB << atPosition; // 00010000 

,然後用它來檢索,清晰設置位值:

// get bit at position 4 
unsigned int valueOfFourthBit = val & mask; 

// clear bit at position 4 and assign to result 
unsigned int res = val & ~(mask); 

// put the value of the 4th bit at wanted position 
int wantedPosition = 21; 
res |= valueOfFourthBit << wantedPosition; 

如果您需要一系列的連接像你的情況3一樣,你可以這樣做:

int numberOfSetBits = 3; 
int setLSBs = 0 

for (int i =0; i < numberOfSetBits; ++i) 
{ 
    setLSBs += (int) Math.Pow(2, i); 
} 

setLSBs = 7; // 00000111 

// and then the masks for getting 3,4,5 and 24,25,26 bits become 
int smallPosition = 3; 
int largePosition = 24; 

int smallMask = setLSBs << smallPosition; // 0x00000034 
int largeMask = setLSBs << largePosition; // 0x07000000; 

其餘的內容都包含在現有的答案中。