Bit operations in the avr c Language

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.