当我尝试代码的不同排列时,我得到奇怪的输出。
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。并且关于c - 奇怪的结果采用XOR的逻辑非,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836852/