Bit operation
One common task is to program the microcontroller MCU to enable or disable some bit of the IO register. Fortunately, standard C has good and applicable bit operation functions, without the help of assembly instructions or other non-standard C structure C defines some bitwise operations that are very useful.
A | B-bitwise OR this expression indicates that A is bitwise OR operated by B in the expression. This is usually used to open some bits. | =
For example, Porta | = 0x80; // open 7 (maximum)
A & B-bitwise AND this operation are useful when checking whether some bits are set to 1. For example:
If (Porta & 0x81) = 0) // check position 7 and position 0
Note that parentheses need to be enclosed around the & operator because they have a lower computing priority than =. This is C.ProgramOne of the reasons for many errors
A ^ B-bitwise XOR or this operation is useful for bitwise inversion. For example, in the following example, 7 is flipped.
Porta ^ = 0x80; // flip position 7
~ A-bitwise inversion. This operation executes a bitwise inversion in the expression. This operation is particularly useful when bitwise AND operation is used to close some bits.
Porta & = ~ 0x80; // close the position 7
This compiler can generate the most ideal machine commands for these operations. For example, SBIC commands can be used in bitwise AND operations for conditional branching Based on bit states.
InC LanguageThe operations of the forward position are as follows:
Portb | = (1 <2); // set the 2nd bits of portb to 1
Portb & = ~ (1 <2); // set the 2nd bits of portb to 0
Portb ^ | = (1 <2); // returns the 2nd-bit anti-portb.
While (portb & (1 <2); // Judge 1
While (! (Portb & (1 <2); // 0