C 将 Short Int 转换为 Unsigned Short

C Convert a Short Int to Unsigned Short

C中的short int包含16位,第一位表示该值是负数还是正数。我有一个 C 程序如下:

int main() {
    short int v;
    unsigned short int uv;
    v = -20000;
    uv = v;
    printf("\nuv = %hu\n", uv);
    return 0;
}

由于 v 的值是负数,我知道变量的第一位是 1。所以我希望程序的输出等于 uv = 52,768 b/c 20,000 + (2^15) = 52,768.

相反,我得到 uv = 45536 作为输出。我的哪一部分逻辑不正确?

您看到的行为可以用 C:

的转换规则来解释

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

2 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.

(此引自C99。)

-20000 不能用 unsigned short 表示,因为它是负数。目标类型是无符号的,因此通过重复添加 65536(即 USHORT_MAX + 1)直到它在范围内来转换值:-20000 + 65536 恰好是 45536.

请注意,此行为由 C 标准强制执行,与负数在内存中的实际表示方式无关(特别是,即使在使用 sign/magnitude or ones' complement 的机器上,它的工作方式也相同)。