gpt4 book ai didi

c - Signed Short (Signed Int16) 乘法解释

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:12 27 4
gpt4 key购买 nike

Signed Short (Signed Int16) 乘法解释?

short ss = -32768; // 0x8000 SHRT_MIN
ss *= (short) -1;
printf ("%d", (int)ss); // Prints -32768

值为 -32768 乘以 -1 的无符号短整型如何成为其自身的机制是什么?我的猜测是 (int)32768 ---> 溢出并回绕到 -32768 但这里没有任何地方要求提升为整数或任何更大的数据类型。

寻找定义此行为的 C 规范部分。

最佳答案

这里没有未定义的行为——假设 int 比 16 位宽。

这个:

ss *= (short) -1;

相当于:

ss = ss * (short)-1;

* 的两个操作数都从short提升int(通过整数提升), 并且乘法在 int 类型中完成。它产生 int32768(同样,除非 INT_MAX == 32767,这是合法的,但在现代非嵌入式系统中很少见)。 (C 没有对窄于 intunsigned int 的整数类型的算术运算。)

int 值被转换回 short。与算术运算不同,当值不适合目标类型时,将整数值转换为有符号整数结果会产生实现定义的结果(或引发实现定义的信号,但我认为没有任何实现这样做)。

32768 转换为 short可能产生-32768

签名转换的行为在 N1570 中指定。 6.3.1.3p3:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

整数提升在 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. All other types are unchanged by the integer promotions.

关于c - Signed Short (Signed Int16) 乘法解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58653861/

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