我有一个问题。在此程序中,变量 x 应设置为 0x10000,但两次操作的结果均为 0。
这不是主程序,而是用于查找错误原因的测试。我目前正在制作一个带有十六进制输入的 64 位乘法器。我使用 Keil 和 Proteus 进行 16 位乘法
int main() {
unsigned long int x = 0;
x = 0x8000 * 0x2;
x = 0x8000 + 0x8000;
return 0;
}
最佳答案
文字0x8000
类型为 unsigned int
。在您的 16 位计算机上,int
因此unsigned int
自然大小为 16 位,是 C 标准所接受的最小大小。整数提升规则规定较小宽度的类型会加宽到 int
或unsigned int
,但仅此而已 (C11 n1570 6.3.1.1p2) :
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 anint
; otherwise, it is converted to anunsigned int
. These are called the integer promotions. 58) All other types are unchanged by the integer promotions.
操作数从 int
扩展而来或unsigned int
仅当其他操作数具有更高的等级时。
在这里,0x8000
+ 0x8000
使用 unsigned int
计算这将换行为 0,因为 unsigned int
中可以表示的最大值是 0xFFFF
.
您应该将至少一个操作数强制为 unsigned long
使用后缀 UL
,或者通过添加显式强制转换:
int main() {
unsigned long int x=0;
/* unsigned long int * int */
x = 0x8000UL * 0x2;
/* unsigned long + unsigned int */
x = (unsigned long)0x8000 + 0x8000;
return 0;
}
<小时/>
关于c - 8051 16 位加法/乘法结果 16 位而不是 32 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693053/