【问题标题】:Performing a logical not ! using only bitwise operations [duplicate]执行逻辑不!仅使用按位运算[重复]
【发布时间】:2010-10-28 05:15:39
【问题描述】:

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

大家好,

我正在处理一个项目,我需要一些有关功能的帮助。我们需要编写一个函数来执行逻辑非,!,只使用以下位运算符:

~ & ^ | + << >>

我什至不知道从哪里开始。

【问题讨论】:

  • @GWW 要么是那个,要么是一个非常奇怪的首席开发人员。 :)
  • 在描述中我说这是一个项目。 :)
  • 是的,但一个项目可能意味着一个家庭作业项目:P
  • 什么项目规范会明确要求您重新实现逻辑运算符?!

标签: c bitwise-operators bits logical-operators


【解决方案1】:

如果您可以假设 true = 1false = 0,那么这可能会成功:

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

【讨论】:

    【解决方案2】:

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

    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);
    }
    

    【讨论】:

      【解决方案3】:

      我想一开始你会想要澄清这个问题。听起来您想要一个函数,如果单词中的任何位都是“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;
      

      【讨论】:

      • 合乎逻辑!对于 0 参数,应该返回 1,而不是 0xffffffff。
      • 对,我还有一个错误。
      猜你喜欢
      • 2017-01-11
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多