2014-12-02 17 views
0
signed short Temp; 
Temp = 0xF2C9; 
Temp2 = 0x100; 

unsigned char a; 
a = (unsigned char)(Temp/((unsigned short)Temp2)); 

预期输出是什么?
按我的理解,由于“常见算术转换”第一Temp应该被转换为unsigned short并导致a应该0xF2,但我得到这意味着操作与Temp签署价值进行响应0xF3。请解释行为。通常的算术转换:意外输出

Endianess在这种情况下是否也有相关性?

+6

不会编译。 'Temp2'未定义。 – 2014-12-02 13:22:49

+0

在进行数学计算之前'Temp'和'(unsigned short)Temp2'都被提升为int。 C中的操作不能在小于int的类型中完成 – 2014-12-02 15:55:44

+0

@LưuVĩnhPhúc在进行数学运算之前,'(unsigned short)Temp2'被提升为int或unsigned。这取决于类型的范围。 – chux 2014-12-02 19:18:54

回答

1

不,首先参数算术运算符促进,即窄类型,如您short s的转换为int。 (至少在所有通用架构上)。

假设short在您的系统上是16位宽,则Temp的初始化是实现定义的,因为0xF2C9的值不适合该类型。很可能这是一个负值。然后,为了计算,该负值signed short值被提升为int。除法结果是负值,然后转换为unsigned char

0

整数除法以“截至零”工作,所以此除法的结果为F3,即-13,而不是F2,即-14。如果你用十进制表示计算这个结果,结果将是-13.21,然后你会减少0.21。

+0

这个答案假定计算是在有符号整数上进行的。问题**为什么**整数已签名,所以答案没有帮助。 – anatolyg 2014-12-02 16:01:45

1

这取决于是否INT_MAX >= USHRT_MAX

“通常算术转换” 转换成Temp(int) Temp。如果intshort宽,这将只会“扩展符号”。

((unsigned short)Temp2)被提升为(int)((unsigned short)Temp2)(unsigned)((unsigned short)Temp2)

如果INT_MAX >= USHRT_MAX,则划分完成为(int)/(int)

否则,就像在一个16位系统上一样,除法完成为(int)/(unsigned),这是作为(unsigned)/(unsigned)完成的。


[编辑]

Temp,与0xF2C9(见注)初始化,可能具有-3383的值(或者具有62153的值应short不大可能是大于16位宽。)

With (int)/(int),-3383/256 - > -13.21 ... - > -13。 -13转换为unsigned char→256-13→243或0xF3。

(假设16位int/unsigned)随着(unsigned)/(unsigned),-3383转换为unsigned 65536 - 3383 - > 62153.256分之62153 - > 242.78 - > 242 242转化为unsigned char - > 242或0xF2。

在这种情况下不相关的码元性。


注:由于@Jens Gustedt指出的那样,当Temp是16位在Temp的值定义的实现。

0

“这个问题问为什么整数签署”

“按我的理解至于因‘常见算术转换’第一温度应该被转换成无符号短......” NO。你错了。有符号的短Temp具有高位设置,因此是负值。转换为int时,该位将扩展到左侧。有签名的短暂Temp2没有高Bt集;演员阵容(无符号短片)无效;它被转换为正整数。负诠释现在除以正诠释,导致一个负值。

在将Temp2转换为int时,您不希望扩展符号位。用途:

a = (unsigned char)(((unsigned short)Temp)/Temp2); 

(我没有测试它,只是理论)

0

延斯,保罗和妇幼保健,

感谢您的澄清。但根据“ISO/IEC 9899第6.3.1.1节

The rank of any unsigned integer type shall equal the rank of the corresponding 
signed integer type, if any. 

和根据6.3.1.8通常的算术转换”下列规则应适用。

If both operands have the same type, then no further conversion is needed. 

Otherwise, if both operands have signed integer types or both have unsigned 
integer types, the operand with the type of lesser integer conversion rank is 
converted to the type of the operand with greater rank. 

**Otherwise, if the operand that has unsigned integer type has rank greater or 
equal to the rank of the type of the other operand, then the operand with 
signed integer type is converted to the type of the operand with unsigned 
integer type.** 

Otherwise, if the type of the operand with signed integer type can represent 
all of the values of the type of the operand with unsigned integer type, then 
the operand with unsigned integer type is converted to the type of the 
operand with signed integer type. 

Otherwise, both operands are converted to the unsigned integer type 
corresponding to the type of the operand with signed integer type 

所以根据上述规则符号的短(整数型)3第一应被转换为无符号短(整数型),然后arithmatic操作应被执行和结果应当是0xF2。