c - 8051 16 位加法/乘法结果 16 位而不是 32 位

标签 c 16-bit integer-arithmetic integer-promotion

我有一个问题。在此程序中,变量 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 标准所接受的最小大小。整数提升规则规定较小宽度的类型会加宽到 intunsigned 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 an int; otherwise, it is converted to an unsigned 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;
}
<小时/>

另请参阅In a C expression where unsigned int and signed int are present, which type will be promoted to what type?供一般性讨论。

关于c - 8051 16 位加法/乘法结果 16 位而不是 32 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693053/

相关文章:

c - "Warning: Linking the shared library against static library is not portable"是什么意思?

c - 如何在 C 中的 for 循环之外使用 for 循环索引(选择排序)

c - do-while 循环 scanf 在读取单个字符时读取两次循环而不是一次

Python 和 16 位 PGM

embedded - 嵌入 D(编程语言)

javascript - JavaScript 和 HTML 中数字的所有数字之和

c - 多线程程序在 HTTPS 请求上崩溃

constants - 在 MIPS 中移动符号扩展常量

c - 此函数输出的说明

algorithm - 如何找到环绕的两个数字的平均值?