检查输入是否为最大2s补码整数

问题描述 投票:0回答:1
/*
 * isTmax - returns 1 if x is the maximum, two's complement number,
 *     and 0 otherwise 
 *   Legal ops: ! ~ & ^ | +
 *   Max ops: 10
 *   Rating: 1
 */
int isTmax (int x) 
{
    int t = x + 1;
    return !(t + t) ^ !t;
}  

如果x是最大的2的补数,则2 * t溢出为0,但如果x为-1则也为0,所以我们用!t对它求和,其结果为1。因此我们必须得到1,但输出为0。

c bit-manipulation bitwise-operators
1个回答
0
投票

此代码从根本上是错误的。有符号的溢出是未定义的行为,不能保证提供任何形式的确定性结果。

要检查数字是否为“最大数”,您宁愿将其与limits.h中的INT_MAX进行比较。或者,如果愿意,可以将其与(int) ((1u<<31)-1)进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.