执行逻辑不!仅使用按位运算

时间:2010-10-28 05:15:39

标签: c bitwise-operators bits logical-operators

  

可能重复:
  Check if a number is non zero using bitwise operators in C.

大家好,

我正在开发一个项目,我需要一个函数的帮助。我们需要编写一个执行逻辑not,!的函数,只使用以下按位运算符:

~ & ^ | + << >>

我甚至不确定从哪里开始。

3 个答案:

答案 0 :(得分:3)

如果你可以假设true = 1false = 0,那么这可能会有所帮助:

bool
not(bool x) {
    bool not_x = x ^ true;
    return not_x;
}

答案 1 :(得分:3)

逻辑不返回0,如果值不为零,否则返回1。假设32位int:

int not_func(int v) {
    /* compress value to single bit */
    int p = (v >> 16) | v;
    p = (p >> 8) | p;
    p = (p >> 4) | p;
    p = (p >> 2) | p;
    p = (p >> 1) | p;

    p ^= 1;
    return (p & 1);
}

答案 2 :(得分:2)

我想开始你想要你澄清这个问题。听起来你想要的是一个函数,如果一个字中的任何一个位为“1”,则返回0,如果所有位都为零则返回0以外的函数。假设一个32位字“a”你可以做类似的事情:

na1 = ~a;
shifted_na1 = na1 >> 1;
na2 = shifted_na1 & na1; /* any sequence of zeros is now 2 bits long */
shifted_na2 = na2 >> 2;
na3 = shifted_na2 & na2; /* any sequence of zeros is now 4 bits long */
shifted_na3 = na3 >> 4;
na4 = shifted_na3 & na3; /* any sequence of zeros is now 8 bits long */
shifted_na4 = na4 >> 8;
na5 = shifted_na4 & na4; /* any sequence of zeros is now 16 bits long */
shifted_na5 = na5 >> 16;
final = shifted_na5 & na5; /* any sequence of zeros is now 32 bits long */
really_final = final & 1;
相关问题