c - 奇怪的结果采用XOR的逻辑非

标签 c

当我尝试代码的不同排列时,我得到奇怪的输出。

int ret = (xCopy ^ x);
return ret; 
// returns -1[0xffffffff]

===============

int ret = !(xCopy ^ x);
return ret;
// returns 1[0x1]


!(-1)不应为0吗?

确实...

int ret = !(-1);
return ret;
// returns 0[0x0]

=============

int ret = !(0xFFFFFFFF);
return ret;
// returns 0[0x0]


这是我的代码

// x = 0x80000000 and n=0x01
int fitsBits(int x, int n) {

  // Grab the sign bit.
  int signBit = (x >> 31) & 0x01;

  // Truncate down to n bits.
  int xCopy = x << (32-n);

  // Set the MSB to 0.
  int msb = (xCopy >> 31) & 0x01;
  int msbMask = ~(0x01 << 31);
  xCopy = xCopy & msbMask;

  // Shift back to word.
  xCopy = xCopy >> (32-n);

  // Restore the MSB
  int restoreMask = msb << (32-n);
  xCopy = xCopy | restoreMask;

  // Restore the sign bit.
  int signBitMask = signBit << 31;
  xCopy = xCopy | signBitMask;

  return !(xCopy ^ x);
}

最佳答案

请提供您的输入值。

我尝试使用这些值,它可以正常工作。

void main()
{
    int t1, t2;
    int xCopy, x;

    xCopy = 0xAAAAAAAA;
    x = 0x55555555;

    t1 = xCopy ^ x;
    printf("%d\n", t1);  //Gives -1 as expected

    t2 = !(xCopy ^ x);
    printf("%d\n", t2);  //Gives 0 as expected
}




您的新代码对我来说很好。根据您的代码和输入,在功能结尾处,在!(xCopy ^ x)xCopy中,x(xCopy ^ x)的值均为0x80000000。

所以!(xCopy ^ x)对我来说是0。并且如预期的那样为1。

关于c - 奇怪的结果采用XOR的逻辑非,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836852/

相关文章:

c - 有没有办法将条件分配转换为无分支代码?

C - 位矩阵的位字段

c - 在从 C 回调期间保护小堆上的指针

C编程: Replacing if statements

c - 字符串 c 的二叉树

c - C 中的泰勒级数,函数先除后乘

c - sockaddr_in 不支持地址族

C 程序读取输入文件并每 50 个字符以 "\n"换行输出

c - 内存泄漏 char* C程序

c - 数组长度计数异常