位操作而不是if用于复制位图

时间:2012-03-22 19:57:19

标签: bitwise-operators

我想避免下面的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 个答案:

答案 0 :(得分: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);