码迷,mamicode.com
首页 > 编程语言 > 详细

[C语言]整型提升

时间:2020-06-17 16:56:03      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:value   地方   优先级   origin   cpu   repr   语言   may   str   

示例:
unsigned ucHigh,ucLow;
unsigned short usValue = ucHigh << 8 + ucLow;

解析:
1、上面的问题在哪呢?是ucHigh值太低,导致移位溢出?
2、还是运算符优先级的问题?

答案是运算符优先级的问题,那溢出不考虑么?下面就解释为啥不考虑
unsigned short usValue = (ucHigh << 8) + ucLow;

"A character, a short integer, or an integer bit-field, all either signed or not, or an object of enumeration type, may be used in an expression wherever an integer maybe used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion."
大意是:表达式中可以使用整数的地方,就可以使用枚举类型,或有符号或无符号的字符、短整数、整数位域。如果一个int可以表示上述类型,则该值被转化为int类型的值;否则,该值被转化为unsigned int类型的值。这一过程被称作integral promotion。
整型提升的意义在于:表达式的整型运算要在CPU的相应运算器件内执行,CPU内整型运算器(ALU)的操作数的字节长度一般就是int的字节长度,同时也是CPU的通用寄存器的长度。因此,即使两个char类型的相加,在CPU执行时实际上也要先转换为CPU内整型操作数的标准长度。通用CPU(general-purpose CPU)是难以直接实现两个8比特字节直接相加运算(虽然机器指令中可能有这种字节相加指令)。所以,表达式中各种长度可能小于int长度的整型值,都必须先转换为int或unsigned int,然后才能送入CPU去执行运算。

所以上述表达式右边的提升到int型进行处理的,所以不会丢失,当然你也可以写代码验证一下哦

[C语言]整型提升

标签:value   地方   优先级   origin   cpu   repr   语言   may   str   

原文地址:https://blog.51cto.com/xjgww/2505216

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!