位运算符有四个:“与(&)”、“或(|)”、“异或(^)”、“按位取反(~)”。
在了解位运算符之前,请先复习逻辑运算符:
小朋友学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
(四)位运算符“按位取反”(~)
运算规则:
~1 = 0
~0 = 1
例4:~1 = -2(这里的-1指的是十进制的-1,二进制为00000000 00000000 00000000 00000001)
分析
计算机是以补码的形式存放整数的。
对于正整数来说,原码、反码、补码一样。
对于负整数来说,补码 = 反码 + 1
1的补码是00000000,00000000,00000000,00000001
使用取反运算符后,变为11111111,11111111,11111111,11111110
注意,这是一个补码。最高位是1,表示它是一个负数。
负数的原码 = 补码 - 1,再取反
11111111,11111111,11111111,11111110 - 1 = 111111111,11111111,11111111,11111101
取反(注意符号位不参与取反)后为10000000,00000000,00000000,00000010
这个数即为十进制的-2
#include <stdio.h>
int main()
{
int a = 1;
printf("~%d = %d", a, ~a);
return 0;
}
运行结果:
~1 = -2
想了解小朋友学编程可加QQ 307591841 或微信 307591841
关注微信公众号请扫二维码
qrcode_for_kidscode_258.jpg
网友评论