gpt4 book ai didi

在 C 中将 signed char 转换为 unsigned int

转载 作者:太空狗 更新时间:2023-10-29 14:55:01 25 4
gpt4 key购买 nike

谁能向我解释为什么以下代码输出 -50,即使它被转换为 unsigned int?

int main()
{
signed char byte = -50;
unsigned int n;

n = (unsigned int) byte;

printf("n: %d", n);
}

输出:-50

最佳答案

-50 赋值给 unsigned int 会导致整数环绕,而环绕 unsigned int 的位设置与signed int 对应于几乎每台计算机都使用的二进制补码表示中的 -50

现在,printf 是一个具有可变数量参数的函数,它根据格式字符串进行解释。 %d 格式用于 signed int 并且 printf 无法知道相应的参数实际上是一个 unsigned int(因为您另有说明)。所以这些位被解释为好像是 signed int 并且你得到 -50

关于在 C 中将 signed char 转换为 unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21948405/

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