Common location operations in C Language

Source: Internet
Author: User

From: http://blog.ednchina.com/jimmy_qiu/78829/message.aspx

 

How to Set 0 or 1 for a certain position?
Method 1: Write a macro to facilitate migration
# Define setbit (x, y) x | = (1 <Y) // set position y of X to 1.
# Define clrbit (x, y) X & =! (1 <Y) // clears the Y position of X to 0. Method 2: In addition to improving the operation efficiency, the C language bit operation is another typical application in embedded system programming, in addition, it is widely used in scenarios such as bitwise AND (&), or (|), non (~) Operation, which is closely related to the programming features of embedded systems. We usually need to set the bit of the hardware register, for example, by setting the Lower 6 bits of the interrupt Shield Control Register of the am186er 80186 processor to 0 (on interrupt 2 ), the most common practice is:

# Define int_i2_mask 0x0040
Wtemp = inword (int_mask );
Outword (int_mask, wtemp &~ Int_i2_mask );

The method to set this bit to 1 is:

# Define int_i2_mask 0x0040
Wtemp = inword (int_mask );
Outword (int_mask, wtemp | int_i2_mask );

To determine whether the bit is 1 is:

# Define int_i2_mask 0x0040
Wtemp = inword (int_mask );
If (wtemp & int_i2_mask)
{
... /* This bit is 1 */
}

Method 3: int A | = (1 <X) // X indicates the number to be set to 1. For example, the fourth position is a | = (1 <4)
Int B & = ~ (1 <X) // set a position 0x = x | 0x0100 // set the third position 1
X = x & 0x1011 // set the third position to 0 # define bitget (number, POS) (number)> (POS) & 1 )) // use a macro to obtain a certain number
# Define bitget (number, POS) (number) | = 1 <(POS) // set a location of 1
# Define bitget (number, POS) (number) & = ~ (1 <(POS) // set a position to 0
# Define bitget (number, POS) (number) ^ = 1 <(POS) // a typical anti-pos operation for Number:
Wtcon | = (1 <5) // The fifth-digit clearance of wtcon 1
Wtcon & = ~ (1 <5) // The fifth digit of wtcon is 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.