2012-03-22 48 views
0

我想避免下面的if語句。我可以以某種方式只使用按位運算符將舊比特數組中的比特位複製到新比特數組中?位操作,而不是如果複製位圖

#define BYTE_POS(pos) (pos/CHAR_BIT) 
#define BIT_POS(pos) (1 << (CHAR_BIT - 1 - (pos % CHAR_BIT))) 

if ((old_array[BYTE_POS(old_pos)] & BIT_POS(old_pos)) != 0) { 
    new_array[BYTE_POS(new_pos)] |= BIT_POS(new_pos); 
} 

回答

1

變化BIT_POS這樣:

#define BIT_POS(pos, state) (state << (CHAR_BIT - 1 - (pos % CHAR_BIT))) 

然後將代碼更改爲:

bool state = (old_array[BYTE_POS(old_pos)] & BIT_POS(old_pos, 1)) != 0); 

new_array[BYTE_POS(new_pos)] |= BIT_POS(new_pos, state);