c - C 中的文字和变量(有符号与无符号短整型)有什么区别?

标签 c bit-manipulation twos-complement unsigned-integer integer-promotion

我在 Computer Systems: A Programmer's Perspective, 2/E 一书中看到了以下代码。这很好用并创建了所需的输出。输出可以用有符号和无符号表示的差异来解释。

#include<stdio.h>
int main() {
    if (-1 < 0u) {
        printf("-1 < 0u\n");
    }
    else {
        printf("-1 >= 0u\n");
    }
    return 0;
}

上面的代码产生 -1 >= 0u ,但是,下面的代码应该和上面一样,但不是!换句话说,

#include <stdio.h>

int main() {

    unsigned short u = 0u;
    short x = -1;
    if (x < u)
        printf("-1 < 0u\n");
    else
        printf("-1 >= 0u\n");
    return 0;
}

产量 -1 < 0u .为什么会这样?我无法解释这一点。

请注意,我已经看到类似的问题,如 this , 但它们无济于事。

附言。正如@Abhineet 所说,可以通过更改 short 来解决困境。至 int .然而,如何解释这一现象呢?换句话说,-1 4 个字节是 0xff ff ff ff在 2 个字节中是 0xff ff .将它们作为 2s 补码,解释为 unsigned , 它们的对应值为 429496729565535 .他们都不少于0我认为在这两种情况下,输出都需要是 -1 >= 0u ,即 x >= u .

它在 little endian Intel 系统上的示例输出:

简而言之:

-1 < 0u
u =
 00 00
x =
 ff ff

对于整数:

-1 >= 0u
u =
 00 00 00 00
x =
 ff ff ff ff

最佳答案

The code above yields -1 >= 0u

所有整数文字(数字常量)都有类型,因此也有符号。默认情况下,它们的类型为 int已签名。当您附加 u后缀,你把文字变成unsigned int .

对于任何有一个有符号操作数和一个无符号操作数的 C 表达式,平衡规则(正式名称:the usual arithmetic conversions)会将有符号类型隐式转换为无符号类型。

从有符号到无符号的转换是明确定义的 (6.3.1.3):

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

例如,对于标准二进制补码系统中的 32 位整数,无符号整数的最大值为 2^32 - 1 (4294967295,limits.h 中的 UINT_MAX)。比最大值大一是2^32 .和 -1 + 2^32 = 4294967295 , 所以字面量 -1转换为值为 4294967295 的无符号整数.大于 0。


然而,当您将类型切换为 short 时,您最终会得到一个小整数类型。这是两个例子的区别。每当一个小整数类型是表达式的一部分时,整数提升规则就会隐式地将其转换为更大的 int (6.3.1.1):

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

如果short小于 int在给定的平台上(如 32 位和 64 位系统的情况),任何 shortunsigned short因此总是会转换为 int ,因为它们可以放在一个里面。

所以对于表达式 if (x < u) ,你实际上最终得到了 if((int)x < (int)u)其行为符合预期(-1 小于 0)。

关于c - C 中的文字和变量(有符号与无符号短整型)有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33339896/

相关文章:

c - C 中的 0/0 - gcc-7 或更高版本

C - 战列舰阵列

python - Python 中的位掩码

C - 或两个位图的最快方法

c++ - 二进制补码形式所需的最少位数

twos-complement - 用2'补码表示负数?

c++ - 使用 qsort 对字符串进行排序不起作用

填充数组的代码突然改变变量(C)

c - 为什么该函数可以正常使用 float 而不能使用 double?

java - 如何将整数转换为十六进制有符号2的补码: