gpt4 book ai didi

C编程。无符号整数评估问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:39 26 4
gpt4 key购买 nike

在 C 编程中我遇到了这个问题:

int v = 0XFFFD;
unsigned z=1;

评估表达式:

a) (v+1)/2  
b) -1 > z

在习题书中,对于
a) 答案是-1,对于
b) 答案是 1

谁能解释一下为什么?
因为在我看来
a) 我认为答案是32767,对于
b) 是 0

最佳答案

案例 1:默认情况下,int 类型是有符号的,这意味着编译将检查符号位,如果符号位是 1,则输出将为负数。

int v = 0XFFFD

v 将如何存储在内存中,如果它是小端,则如下所示

    -------------------------
| 1111 1111 | 1111 1101 |
-------------------------
MSB LSB
v

如您所见,符号位(第 15 位,在 short int 的情况下)为 1,负数作为二进制补码存储在内存中。 v i 的补语是

 one's compliment =>  0000 0000 |  0000 0010
+1
-----------------------
0000 0000 | 0000 0011 => 3 and since sign bit is one that's why v is -3

当你在做 (v+1)/2 == (-3+1)/2 => -1

案例二:

unsigned z = 1;

假设语句看起来像

printf("%d\n", -1 > z);

在这里,在两个操作数之间执行任何操作时,您应该了解操作数类型不同的后果。

 -1  >  z
| | => comparing different operands
signed unsigned (one is signed and other one unsigned) => Implicit type conversion will happen i.e implicitly signed gets promoted into unsigned by compiler)
||
65535 > 1 => true => pints 1
|
(-1 is signed and its converted into unsigned and unsigned equivalent of -1 is 65535 in case of shot integer)

关于C编程。无符号整数评估问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com