当前位置:网站首页>[C language] deeply understand integer lifting and arithmetic conversion
[C language] deeply understand integer lifting and arithmetic conversion
2022-07-26 02:52:00 【ecember】
Technical nerd , Save the world !
author :@ecember
special column :《 from 0 Start ——C Language 》
To readers : People who believe in miracles are as great as miracles
| Thank you for give the thumbs-up and Focus on , If you need to see my homepage column |
List of articles
1. Preface
The happiest thing in life is to fight , Not success , The most painful thing in life is laziness , Not failure . Hello everyone , Here is ecember. Today, let's talk about the headache of integer promotion and arithmetic conversion , Finally, the priority of operators is sorted into a table .( The following results are in VS2022 Compile in )
2. Expression evaluation
The order in which expressions are evaluated is partly determined by the precedence and associativity of the operators . Again , The operands of some expressions may need to be converted to other types during evaluation .
2.1 Implicit type conversion
C Integer arithmetic operations are always performed at least with the precision of the default integer type . To get this accuracy , Characters and short operands in expressions are converted to normal integers before use , This transformation is called Improve the overall shape
The significance of integer Promotion :
<1> The integer operation of expression should be in CPU In the corresponding computing device of ,CPU Inner integer arithmetic unit (ALU) The byte length of the operands of is generally int Byte length of , It's also CPU The length of the general register of . therefore , Even two char The addition of types , stay CPU When executing, it should be converted to CPU The standard length of the inner operands .
<2> Universal CPU(general-purpose CPU) It is difficult to realize two directly 8 Direct addition of bits and bytes ( Although there may be such byte addition instructions in machine instructions ). therefore , Various lengths in expressions may be less than int The integer value of the length , Must be converted to int or unsigned int, Then it can be sent in CPU To perform the operation .
Next , We will thoroughly explain this integer promotion based on a set of examples .
int main()
{
char c1 = 3;
//00000000000000000000000000000011
//00000011 - c1 - char Can only save 8 individual bit position
char c2 = 127;
//00000000000000000000000001111111
//01111111 - c2
char c3 = c1 + c2;
// Improve the overall shape - A positive high complement 0
//00000000000000000000000000000011-c1
//00000000000000000000000001111111-c2
//00000000000000000000000010000010-c3
//10000010-c3 - Negative high complement 1
//11111111111111111111111110000010-c3 Complement code
//10000000000000000000000001111101
//10000000000000000000000001111110-c3 Original code
printf("%d\n", c3);
return 0;
}
The original code printed out is just -126, Let's see the result .
We conclude from the above examples The law of integer lifting .
Integer promotion is promoted according to the sign bit of the data type of the variable .
Integer promotion of negative numbers
char c1 = -1;
Variable c1 Binary bit of ( Complement code ) There are only 8 A bit :1111111
because char by A signed Of char
So when shaping and improving , High level supplement Sign bit , That is to say 1
The result of ascension is :
11111111111111111111111111111111
Integer promotion of positive numbers
char c2 = 1;
char c2 = 1;
Variable c2 Binary bit of ( Complement code ) There are only 8 A bit :00000001
because char For signed char
So when shaping and improving , High level supplement Sign bit , That is to say 0
The result of ascension is :
00000000000000000000000000000001
unsigned Type integer
No sign plastic lift , High compensation 0.
example 1
int main()
{
char a = 0xb6;//10110110- Negative after integer promotion
short b = 0xb600;//1011011000000000
int c = 0xb6000000;//int Type does not require integer elevation
if (a == 0xb6)// The comparison operation requires integer promotion
printf("a");
if (b == 0xb600)
printf("b");
if (c == 0xb6000000)
printf("c\n");
return 0;
}

example 2
int main()
{
char c = 1;
printf("%u\n", sizeof(c));//1
printf("%u\n", sizeof(+c));// Improve the overall shape 4
printf("%u\n", sizeof(-c));//4
return 0;// Anyone who char Variables of type participate in expression evaluation, and integer promotion will occur
}

2.2 Arithmetic conversion
If the operands of an operator belong to different types , Then unless one of the operands is converted to the type of the other operand , Otherwise, the operation cannot be carried out . The following hierarchy is called Ordinary arithmetic conversion .
<1> long double
<2> double
<3> float
<4> unsigned long int
<5> long int
<6>unsigned int
<7> int
If the type of an operand is in the above list Low ranking , Well, first of all Convert to another operand type Post execution operation .
Warning :
But the arithmetic conversion should be reasonable , Otherwise there will be some potential problems .
float f = 3.14;
int num = f;// Implicit conversion , There will be loss of accuracy
2.3 The properties of the operator
There are three factors that affect the evaluation of complex expressions .
1. The priority of the operator
2. The associativity of operators
3. Whether to control the order of evaluation
Which of the two adjacent operands should be executed first ? Depending on their priorities . If both have the same priority , Depending on their combination .
Here is Operator priority list , You can save ang .


2.4 Some problem expressions
expression 1
a*b + c*d + e*f
notes : Code 1 When calculating , because * Than + High priority , Only guarantee ,* The calculation is better than + Good morning! , But priority does not determine the third * Better than the first + Early execution .
So there may be many orders .
// The order 1
a*b
c*d
a*b + c*d
e*f
a*b + c*d + e*f
// The order 2
a*b
c*d
e*f
a*b + c*d
a*b + c*d + e*f
expression 2
c + --c;
notes : ditto , The priority of the operator can only determine self subtraction – The operation of is + Before the operation of , But we have no way to know ,+ Whether the left operand of the operator is evaluated before or after the right operand , So the results are unpredictable , There is ambiguity .
expression 4
This expression is illegal . expression 3 Test results in different compilers :
3. Integer lifting exercise
What does the following code output ?
int main()
{
unsigned char a = 200;
unsigned char b = 100;
unsigned char c = 0;
c = a + b;
printf("%d %d", a + b, c);
return 0;
}
From what we said earlier char When type data participates in expression operation , Integer promotion will occur , But if you put it into a char Type data will be truncated .
int main()
{
unsigned char a = 200;
//000000000000000000000000 11001000
unsigned char b = 100;
//000000000000000000000000 01100100
unsigned char c = 0;
//000000000000000000000000 00000000
c = a + b;
//000000000000000000000001 00101100 - a + b
//00101100 - truncation - c
printf("%d %d", a + b, c);//300 44
return 0;
}
4. Conclusion
Here we are , our 《 In depth understanding of Improve the overall shape and Arithmetic conversion 》 It's near the end , I will continue to update later C Language related content , Endless learning , It will always be left to those who are prepared . I hope my blog can help you , If you like it, you can give the thumbs-up + Collection Oh , You are also welcome to point out my mistakes in the comment area at any time .
边栏推荐
- Arthas download and startup
- Usage of arguments.callee
- ERROR: could not extract tar starting at offset 000000000000020980+9231072+2
- Wechat official account mutual aid, open white groups, and small white newspaper groups to keep warm
- numpy.sort
- Usage of fuser and lsof
- Neo4j 导入csv数据报错:Neo4j load csv error : Couldn‘t load the external resource
- Image recognition (VII) | what is the pooling layer? What's the effect?
- How can users create data tables on Web pages and store them in the database
- pbootcms上传缩略图尺寸自动缩小变模糊
猜你喜欢

Handling process of the problem that the virtual machine's intranet communication Ping fails

Project management: lean management method
![[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)](/img/b8/56c4541602c5a6e787e2455f80febd.png)
[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)

MySQL教程:MySQL数据库学习宝典(从入门到精通)

JS get the time composition array of two time periods

Binary search 33. search rotation sort array
![[reading notes] user portrait methodology and engineering solutions](/img/5e/916853accf3a5af237f7f114855437.jpg)
[reading notes] user portrait methodology and engineering solutions

AMD64(x86_64)架构abi文档:中

DFS Niuke maze problem

Literature speed reading | in the face of danger, anxious people run faster?
随机推荐
Case: using kept+haproxy to build a Web Cluster
Personally test five efficient and practical ways to get rid of orders, and quickly collect them to help you quickly find high-quality objects!
How to effectively prevent others from wearing the homepage snapshot of the website
Image recognition (VI) | activation function
织梦提示你设定了字段为联动类型如何解决
Article setting top
Simply use MySQL index
关于mysql的问题,希望个位能帮一下忙
Be highly vigilant! Weaponization of smartphone location data on the battlefield
Exclusive interview with ringcentral he Bicang: empowering future mixed office with innovative MVP
Autojs cloud control source code + display
Handling process of the problem that the virtual machine's intranet communication Ping fails
HLS Experiment 1 -- multiplier
微信公众号互助、开白群,小白报团取暖
ShardingSphere数据分片
Overview of pytoch's API
DFS Niuke maze problem
I hope you can help me with MySQL
1. Software testing ----- the basic concept of software testing
MySQL build websites data table
