C bitwise operators

1 Introduction

C bitwise operators have & (bitwise and), | (bitwise OR), ^ (bitwise exclusive or) ~ (bitwise), the bitwise operation object as a binary bits of bit string information, specified by the operation completion position, the corresponding results.

 

2, bitwise operator

In the above-mentioned operator, ~ (bitwise negation) of unary operator, others are binary operators, bitwise operators highest to lowest priority, followed by ~, &, ^, |.

(1) bitwise AND operator (&)

Bitwise AND operator is calculated according to the following rules:

0 & 0 = 0

0 & 1 = 0

1 & 0 = 0

1 & 1 = 1

That is the same as the position 1, the result is 1, and 0 otherwise.

Bitwise AND two typical usage, a first bit string is to take a few, e.g., taken lowest 8 bits x: x & 0x00ff, the second is to make a reservation several variables, rest position 0, e.g. let x retains high 8: x = x & 0xff00.

(2) bitwise OR operator (|)

Bitwise OR operator calculated according to the following rules:

0 | 0 = 0

0 | 1 = 1

1 | 0 = 1

1 | 1 = 1

That is, as long as there is a bit of an operation result is 1, the remainder is 0.

Bitwise OR operator typical usage of certain position is a 1 information bit string, for example, 2 x the lowest position of 1: x = x | 0x03.

(3) bitwise exclusive OR operator (^)

Bitwise exclusive OR operator calculated according to the following rules:

0 ^ 0 = 0

0 ^ 1 = 1

1 ^ 0 = 1

1 ^ 1 = 0

That is, the corresponding bit of the same value, the result is 0, the corresponding bit of different values, compared with 1.

(4) bitwise operator (~)

Bitwise unary operation is used to find a bit string of information bit counter, i.e., 0 bits of which, as a result of operation, and which is 1 bit, the result is 0, for example, x value of 0x07, the result is ~ x 0xf8.

Typical applications negated bitwise operators, for use in conjunction operator and &, 0 is set to be a few, e.g., 2 x minimum bit cleared operation, x is 0xf3, then clear the lowest 2 0, can x = x & ~ 0x03, after running the statement, x becomes 0xf0.

Guess you like

Origin www.cnblogs.com/Cqlismy/p/11773381.html