小朋友学C语言(24):位运算符
位运算符有三个:“与(&)”、“或(|)”、“异或(^)”。
在了解位运算符之前,请先复习逻辑运算符:
小朋友学C语言(12):逻辑运算符
位运算,就是对应的bit参与运算,结果是整型数。
逻辑运算,是两个逻辑变量(0或1,非0都算做1)参与运行,结果是逻辑值(0或1)。
(一)位运算符“与”(&)
运算规则:
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
例1:13 & 6 = 4
注意:13在计算机里实际占32位,在1101的左边还有28个0,为了表示简便,将左侧的28个0都省略了。
同样,6的二制式形式0100的最左边也有28个0。
编程验证:
#include <stdio.h>
int main()
{
int a = 13;
int b = 6;
int result = a & b;
printf("%d & %d = %d\n", a, b, result);
return 0;
}
运行结果:
13 & 6 = 4
(二)位运算符“或”(|)
运算规则:
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
例2:13 | 2 = 15
程序验证:
#include <stdio.h>
int main()
{
int a = 13;
int b = 2;
printf("%d & %d = %d\n", a, b, a | b);
return 0;
}
运行结果:
13 & 2 = 15
(三)位运算符“异或”(^)
运算规则(相同为0,不同为1):
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
例3:13 ^ 7 = 10
验证程序:
#include <stdio.h>
int main()
{
int a = 13;
int b = 7;
printf("%d & %d = %d\n", a, b, a ^ b);
return 0;
}
运行结果:
13 & 7 = 10
更多内容请关注微信公众号
还没有评论,来说两句吧...