gpt4 book ai didi

c - 带有 unsigned long long 的符号扩展

转载 作者:太空狗 更新时间:2023-10-29 14:59:40 27 4
gpt4 key购买 nike

我们发现生成了一些奇怪的值,下面是一个小测试用例。这将打印 "FFFFFFFFFF9A64C2A"。这意味着 unsigned long long 似乎已被符号扩展。但为什么 ?下面的所有类型都是无符号的,那么符号扩展是做什么的呢?预期输出将是“F9A64C2A”。

#include <stdio.h>

int main(int argc,char *argv[])
{
unsigned char a[] = {42,76,166,249};

unsigned long long ts;
ts = a[0] | a[1] << 8U | a[2] << 16U | a[3] << 24U;

printf("%llX\n",ts);


return 0;

}

最佳答案

在表达式 a[3] << 24U 中, a[1]类型为 unsigned char .现在,“整数提升”将其转换为 int因为:

The following may be used in an expression wherever an int or unsigned int may be used:

[...]

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

( (draft) ISO/IEC 9899:1999 , 6.3.1.1 2)

另请注意,移位运算符(大多数其他运算符除外)执行“通常的算术转换”,将两个操作数转换为通用类型。但是

The type of the result is that of the promoted left operand.

(6.5.7 3)

在 32 位平台上,249 << 24 = 4177526784解释为 int已设置其符号位。

只是改成

ts = a[0] | a[1] << 8 | a[2] << 16 | (unsigned)a[3] << 24;

解决了这个问题(常量的后缀 U 没有影响)。

关于c - 带有 unsigned long long 的符号扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7554560/

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