在 Jens Gustedt 的《Modern C》一书中,第 59 页,他解释了如何使用无符号整数来模拟有符号整数。 他的示例代码展示了如何实现将两个无符号整数重新解释为有符号整数的比较:
bool is_negative(unsigned a) {
unsigned const int_max = UINT_MAX /2;
return a > int_max;
}
bool is_signed_less(unsigned a, unsigned b) {
if (is_negative(b) && !is_negative(a)) return false;
else return a < b;
}
我是否误解了这里的某些内容,或者他是否错过了第二个特殊情况,其中
is_negative(a) = true
和is_negative(b) = false
?
例如,如果我们想要
a = -1
和 b = 1
,那么,使用补码,我们会将它们表示为
unsigned int a = UINT_MAX;
unsigned int b = 1;
(例如,对于 4 位整数,我们将有 a = 1111 和 b = 0001)。 现在我们有
is_negative(a)
返回 true
,并且 is_negative(b)
返回 false
。当调用 is_signed_less(a, b)
时,我们最终会进入 else
子句,并且 a < b
(现在解释为无符号整数)将返回 false。然而,-1 < 1, so the function returns the wrong result. 显然是正确的
这是书上代码中的拼写错误还是有什么我不明白的地方?
假设我们使用 2 补码表示,它看起来像是一个错误。我会写
return is_negative(a) && !is_negative(b) || a < b;
(我也会为它编写一些测试)。