Lesson 8, Operators and Expressions (Bitwise Operators)
Friends who have learned assembly know that assembly has a strong ability to process bits, but the microcontroller C language can also perform bitwise operations on the operation objects, so that the microcontroller C language can also have a certain ability to directly operate on the hardware. The role of the bit operator is to operate on the variable bit by bit, but it does not change the value of the variable involved in the operation. If you need to change the value of the variable bit by bit, you must use the corresponding assignment operation. In addition, the bit operator cannot be used to operate on floating-point data. There are 6 bit operators in the microcontroller C language. The general expression of bit operations is as follows:
Variable 1 Bitwise Operator Variable 2 Bitwise operators also have priorities, from high to low: "~" (bitwise inversion) → "《《" (left shift) → "》》" (right shift)
Shift) → "&" (bitwise AND) → "^" (bitwise XOR) → "|" (bitwise OR)
Table 8-1 is the truth table of bitwise logic operators. X represents variable 1 and Y represents variable 2.
Table 8-1 Logical truth table for bitwise inversion, AND, OR, and XOR
Using the experimental board built before, we will do an experiment to verify whether the bit operation really does not change the value of the variables involved, and learn the expression of bit operations. The program is very simple. Use P1 port as the operation variable. P1.0-P1.7 corresponds to the lowest bit to the highest bit of the P1 variable. Through the LED connected to the P1 port, we can intuitively see whether the variable has changed or how it has changed after each bit operation. The program is as follows:
#include 《at89x51.h》
void main(void)
{
unsigned int a;
unsigned int b;
unsigned char temp; //temporary variable
P1 = 0xAA; //Light up D1, D3, D5, D7 The binary value of port P1 is 10101010, and the LED is lit when it is 0
for (a=0;a<1000;a++)
for (b=0;b<1000;b++); //delay
temp = P1 & 0x7; //Simply writing P1|0x7 is meaningless, because no variable is affected and it will not be compiled
//After executing P1|0x7, the result is stored in temp. At this time, it is temp that is changed, but P1 will not be affected.
//At this time, the LEDs do not change, and D1, D3, D5, and D7 are still on.
for (a=0;a<1000;a++)
for (b=0;b<1000;b++); //delay P1 = 0xFF; //turn off LED
for (a=0;a<1000;a++)
for (b=0;b<1000;b++); //delay
P1 = 0xAA; //Light up D1, D3, D5, D7 The binary value of port P1 is 10101010, and the LED is lit when it is 0
for (a=0;a<1000;a++)
for (b=0;b<1000;b++); //delay
P1 = P1 & 0x7; //At this time, only D2 will be off.
//Because before P1=0xAA=10101010
// and 0x7 0x7=00000111
//Store the result in P1 P1=00000010 //When the bit is 0, turn on the LED. For the circuit, see Lesson 3
for (a=0;a<1000;a++)
for (b=0;b<1000;b++); //delay P1 = 0xFF; //turn off LED
while(1);
//You can use the above program to do bitwise OR, left shift, negation, etc.
}
Compound assignment operators
Compound assignment operators are simply assignment operators with other operators added before the "=" operator. The following are compound assignment operators in C:
%= modulo assignment -= logical negation assignment
The general form of the left shift assignment compound operation is:
The meaning of the variable compound assignment operator expression is that the variable and expression are first operated as required by the operator, and then the result of the operation is assigned to the variables involved in the operation.
Variables. In fact, this is a method of simplifying programs in C language. All binary operations can be simplified by using compound assignment operators. For example:
a+=56 is equivalent to a=a+56
y/=x+9 is equivalent to y=y/(x+9) Obviously, using compound assignment operators will reduce the readability of the program, but it can simplify the program code and
It can improve the efficiency of compilation. For those who are just starting to learn C language, it is better to use the program expression method according to their own understanding and habits when programming, and do not blindly pursue the shortness of program code
.
If you have programming experience, you will be familiar with the role of commas. For example, in VB, the comma in "Dim a, b, c" is used to define multiple variables as variables of the same type. The same is true in C, such as "int a, b, c". These examples show that commas are used to separate expressions. But in C language, commas are also a special operator, that is, the comma operator, which can be used to connect two or more expressions to form a comma expression. The general form of a comma expression is:
expression1, expression2, expression3...expressionn
When the program is running, the expression composed of the comma operator calculates the value of each expression from left to right, and the value of the entire expression composed of the comma operator is equal to the value of the rightmost expression, which is the value of "expression n". In practical applications, in most cases, the purpose of using comma expressions is just to get the value of each expression separately, and it is not necessary to get and use the value of the entire comma expression. It should also be noted that not all commas appearing in any position of the program can be considered as comma operators. For example, the commas in the parameters of the function and the definitions of the same type of variables are only used for separation and not as comma operators.
Conditional Operators
As we said above, there is a ternary operator in the MCU C language, which is the "?:" conditional operator, which requires three operands. It can connect three expressions to form a conditional expression. The general form of the conditional expression is as follows:
Logical expression? Expression 1: Expression 2 The function of the conditional operator is to select the value of the expression to be used based on the value of the logical expression.
When the value of the logical expression is true (non-zero), the value of the entire expression is the value of expression1; when the value of the logical expression is false (non-zero), the value of the entire expression is the value of expression1;
is 0), the value of the entire expression is the value of expression 2. It should be noted that the type of the logical expression in the conditional expression can be different from the type of expression 1 and expression 2. The following is an example of a logical expression.
If a=1, b=2, then we need to take the smaller value of ab and put it into the min variable. You might write it like this:
if (a < b)
min = a;
else
min = b; //This paragraph means that when a < b, the value of min is the value of a, otherwise it is the value of b.
Using conditional operators to form conditional expressions becomes simple and clear:
min = (a < b)? a : b Obviously, its result and meaning are the same as the above program, but the code is much less than the previous program, and the compilation efficiency is relatively high. However, it has the same disadvantage as compound assignment expressions, which is that the readability is relatively poor. In actual application, you should use it according to your own habits. For me, I like to use a more readable method and add appropriate annotations, which can help debug and write the program, and also facilitate future modification and reading.
Previous article:A complete guide to MCU C language knowledge points (Part 1)
Next article:A collection of typical MCU essay competition questions (Part 1)
Recommended ReadingLatest update time:2024-11-16 15:50
- Popular Resources
- Popular amplifiers
- Wireless Sensor Network Technology and Applications (Edited by Mou Si, Yin Hong, and Su Xing)
- Modern Electronic Technology Training Course (Edited by Yao Youfeng)
- Modern arc welding power supply and its control
- Small AC Servo Motor Control Circuit Design (by Masaru Ishijima; translated by Xue Liang and Zhu Jianjun, by Masaru Ishijima, Xue Liang, and Zhu Jianjun)
- High signal-to-noise ratio MEMS microphone drives artificial intelligence interaction
- Advantages of using a differential-to-single-ended RF amplifier in a transmit signal chain design
- ON Semiconductor CEO Appears at Munich Electronica Show and Launches Treo Platform
- ON Semiconductor Launches Industry-Leading Analog and Mixed-Signal Platform
- Analog Devices ADAQ7767-1 μModule DAQ Solution for Rapid Development of Precision Data Acquisition Systems Now Available at Mouser
- Domestic high-precision, high-speed ADC chips are on the rise
- Microcontrollers that combine Hi-Fi, intelligence and USB multi-channel features – ushering in a new era of digital audio
- Using capacitive PGA, Naxin Micro launches high-precision multi-channel 24/16-bit Δ-Σ ADC
- Fully Differential Amplifier Provides High Voltage, Low Noise Signals for Precision Data Acquisition Signal Chain
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- Open source Linux phone designed with KiCad
- MSP430F5529 MCP4725 Program
- [STM32WB55 Review] This Nucleo is a little special
- HIFU ultrasonic knife (high energy focusing control circuit)
- ARM transplantation encounters a long wait for a solution
- Single bus temperature sensor DS18B20 reading and writing example
- Using C language editor
- Why does this error always occur in the joint simulation of Xilinx 12.4 and modelsim?
- 【K210 Series】3. Core board connection
- The problem of repeated declaration of global variables in embedded C programming