简体   繁体   English

32位系统中的无符号短整数提升

[英]unsigned short integer promotion in 32-bit system

I have a 32-bit integer size 我有32位整数

if I have an arithmetic expression like 如果我有一个算术表达式

unsigned short current_time, last_time
if((current_time - last_time) > timeout)

I believe current_time and last_time will both be converted to signed int 32 before the subtraction. 我相信current_time和last_time都将在减法之前转换为带符号的int 32。 There are no problems with a 16-bit integer size system, but with this 32-bit integer size system will there be potential for a negative value because of the integer promotion? 16位整数大小的系统没有问题,但是对于32位整数大小的系统,由于整数提升,是否有可能出现负值?

If current_time is greater than or equal to last_time , there won't be potential for a negative value. 如果current_time大于或等于last_time ,则不可能存在负值。

To quote section 6.2.1.2 "Signed and unsigned integers" of the C90 spec: 引用C90规范的6.2.1.2节“有符号和无符号整数”:

When a value with integral type is converted to another integral type, if the value can be represented by the new type, its value is unchanged. 将具有整数类型的值转换为另一种整数类型时,如果该值可以用新类型表示,则其值不变。

With unsigned short being shorter than int , all values of type unsigned short can be represented by int , so the converted-to- int values of current_time and last_time will be the same as their un-converted unsigned short value, and the result of the subtraction will be what you expect it to be. 如果unsigned short的长度短于int ,则所有unsigned short类型的值都可以由int表示,因此current_timelast_time的转换为int值将与它们的未转换的unsigned short值相同,并且减法将是您期望的。

If, however, current_time is less than last_time , there is potential for a negative value; 但是,如果current_time 小于 last_time ,则可能为负值; that, however, is not a bug, it's a feature, because, in that case, time really did go backwards. 然而,这是不是一个错误,这是一个特点,因为,在这种情况下,时间真的倒退。

If current_time and last_time were unsigned int s, and current_time were less than last_time , the result of the subtraction would be an unsigned int , and thus not negative; 如果current_timelast_timeunsigned int ,并且current_time小于last_time ,则减法的结果将是unsigned int ,因此不是负数; it would be the difference between the times, modulo the maximum value of an unsigned int . 这将是时间之间的差,以unsigned int的最大值为模。

You probably want to handle time going backwards specially, anyway, if it can happen. 如果可能的话,您可能想专门处理时间倒退。

根据现代C规则,无符号短裤将提升为有符号整数,并且差异将根据其原始值正确签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM