c - 在不使用 '-' 运算符的情况下减去两个数字

标签 c bit-manipulation

我尝试使用以下代码,但我不明白为什么它会给我错误的答案。我正在计算 2 的补码并加上另一个数。

#include <stdio.h>

int add(int a, int b) {
    while (a) {
        a = (a & b) << 1;
        b = a^b;
    }
    return b;
}

int sub(int a, int b) // add a with b's 2's complement.
{
    return (add(a, add(~b, 1)));
}

int main() {
    int a, b, res;
    a = 3, b = 1;
    res = sub(a, b);
    printf("%d\n", res);
    return 0;
}

最佳答案

我按照 NullUserException 的建议使用了不同的 add() 函数,它现在可以工作了:

int add(int a,int b)
{
  int x;
  x = a^b;

  while(a&b)
  {
    b = ((a&b)<<1);
    a = x;
    x = a^b;
    //b=(a^b);
  }

  return x;
}

关于c - 在不使用 '-' 运算符的情况下减去两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3430651/

相关文章:

c - C中setjmp和longjmp的实际使用

c - 在C中用无符号值范围表示有符号值范围

c - 对 byte 和 int 进行按位运算

c - 为什么以下数组操作是非法的?

c - 有没有办法在 C 文件中找到特殊字符 '\n' 的位置?

c - 即使我设置了数组的大小,如何找到输入字符串的长度

c - 指针减法混淆

c# - 字节数组的 Base-N 编码

将 14 位转换为 8 位并返回

c - 将表示有符号整数的字节数组转换为整数的公式