【问题标题】:overflow when multiplying unsigned chars?乘以无符号字符时溢出?
【发布时间】:2011-06-07 14:16:37
【问题描述】:

当我像这样在 C 中将两个无符号字符相乘时:

unsigned char a = 200;
unsigned char b = 200;
unsigned char c = a * b;

然后我知道我会溢出,结果我得到 (40'000 modulo 256)。当我这样做时:

unsigned char a = 200;
unsigned char b = 200;
unsigned int c = (int)a * (int)b;

我会得到正确的结果 40'000。但是,我不知道这会发生什么:

unsigned char a = 200;
unsigned char b = 200;
unsigned int c = a * b;

我可以确定正确的事情发生了吗?这个编译器依赖吗?同样,我不知道做减法时会发生什么:

unsigned char a = 1;
unsigned char b = 2;
int c = a - b;

当使“c”成为无符号字符时,我可能会得到 255。当我使用这样的 int 时会发生什么?

【问题讨论】:

    标签: c casting char overflow int


    【解决方案1】:

    算术运算符的参数得到“通常的算术提升”。

    在 int 可以表示所有操作数的所有值的情况下(大多数实现中的示例就是这种情况),参数首先转换为 int。所以在这两种情况下,你都会得到正确的结果。

    【讨论】:

    【解决方案2】:

    从这个答案复制In a C expression where unsigned int and signed int are present, which type will be promoted to what type?

    6.3.1.3 有符号和无符号整数

    1当一个整数类型的值转换为_Bool以外的其他整数类型时,如果该值可以用新的类型表示,则不变。

    2 否则,如果新类型是无符号的,则在新类型可以表示的最大值的基础上重复加或减一,直到>值在新类型的范围内。

    3 否则,新类型是有符号的,值不能在其中表示; >结果是实现定义的,或者引发了实现定义的信号。

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2012-02-29
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多