Review the C-language bit operations

Source: Internet
Author: User
Tags bitwise

0X01: Bitwise AND (&)

Role:

1) Clear Zero. If you want a cell to be zeroed, even if all of its bits are 0

2) Take some of the points in a number to locate. Those positions that are about to want 1.

Example: If you have an integer a (2 bytes), you want the low byte, just A and (377,8 = = 00000000 11111111) bitwise and can be.

3) which one to keep, with a number & operation, this number in this bit takes 1.

0X02: Bitwise OR (|)

Role:

Often used to set the value of some bits of a data 1, example: A (16-bit integer), a|0377, low 8-bit full 1, high 8-bit remains the same

0x03: xor (^)

Role:

1) Flip the specific bit

Suppose there are 01111010, want to make it low 4-bit flip, that is, 1 to change 0,0 1,. It can be performed with the 00001111 ^ operation.

2) with 0-phase ^ retain original value

3) Exchange two values without temporary variables

Suppose a=3,b=4

A=a^b;

B=b^a;

A=a^b;

0X03: Take the reverse (~)

Role:

For an integer, if you want the lowest one to be 0, you can use a a=a&~1; with better consistency (the ~ operator precedence is higher than the arithmetic operator, the relational operator, the logical operator, and other operators)

0X03: Shift Left (<<)

Role:

High-left shift after overflow, discard.

Generally used to take low

0X04: Right Shift (>>)

Role:

Lower right shift is discarded, on unsigned number, high 0

Generally used to take low

Shift right one is equivalent to dividing by 2, right shift n is equivalent to dividing by 2 n times

Note: When you move right, you need to be aware of the problem with the sign bit. For unsigned numbers, the left high position is shifted to 0 for the signed number, if the original sign bit is 0 (the number is positive), the left is also moved in 0, if the sign bit is 1 (that is, negative), then the left-hand side is 0 or 1, depending on the computer system.





Review the C-language bit operations

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.