# C 语言中的位运算符

## 1. 位运算符

& 位与 a&b
| 位或 a|b
^ 位异或 a^b
~ 位非 ~b
<< 位左移 a<<b
>> 位右移 a>>b

x y x & y x | y x ^ y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

x ~x
0 1
1 0

## 2. 示例

``````# include <stdio.h>

int main()
{
int x,y,z;
x=10; // 10 = 1010
y=15; // 15 = 1111
z=x&y;
printf("x & y = %d\n", z);
z=x|y;
printf("x | y = %d\n", z);
z=x^y;
printf("x ^ y = %d\n", z);
z=~x;
printf("~ x = %d\n", z);
z=~y;
printf("~ y = %d\n", z);
z=x<<2;
printf("x << 2 = %d\n", z);
z=y>>2;
printf("x >> 2 = %d\n", z);
return 0;
}
``````

``````x & y = 10
x | y = 15
x ^ y = 5
~ x = -11
~ y = -16
x << 2 = 40
x >> 2 = 3
``````

``````     10 = 1 0 1 0
15 = 1 1 1 1
10 & 15 = 1 0 1 0
``````

``````     10 = 1 0 1 0
15 = 1 1 1 1
10 | 15 = 1 1 1 1
``````

``````     10 = 1 0 1 0
15 = 1 1 1 1
10 ^ 15 = 0 1 0 1
``````

``````  10 = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
~ 10 = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1
``````

``````  15 = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
~ 15 = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0
``````

``````     10 =     1 0 1 0
10 << 2 = 1 0 1 0 0 0
``````

Tips：请特别注意，在向左移位的过程中，如果左移的位数超出数据的存储最大位数，那么将产生错误。

``````# include <stdio.h>

int main()
{
int x,y,z;
x=10; // 10 = 1010
z=x<<200;
printf("x << 200 = %d\n", z);
return 0;
}
``````

``````test.c: In function ‘main’:
test.c:7:8: warning: left shift count >= width of type [-Wshift-count-overflow]
z=x<<200;
``````
``````     15 = 1 1 1 1
15 >> 2 = 0 0 1 1
``````