C语言之位运算
逻辑位运算均以位(bit)为单位。
逻辑运算符:
· 位“与”:&
· 位“异或”:^
· 位“或”:|
· 位“非”(取反):~
移位运算符:
· 左移:<<
· 右移:>>
&按位与
二元运算符&通过逐位比较两个运算对象,生成一个新值。对于每个位,只有两个运算对象中相应的位都为1时,结果才为1(只有当两个位都为“真”时结果才为“真”)
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
/*
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
1 & 1 = 1
*/
int main(void){
int a = 147; // 1001 0011
int b = 61; // 0011 1101
printf("%d\n",a & b);
system("pause");
return 0;
}
// output:
// 17 (0001 0001)
|按位或
通过逐位比较两个运算对象生成一个新值。运算法则不详细说了,与逻辑运算中的“或”含义相同。
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
/*
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
1 | 1 = 1
*/
int main(void){
int a = 147; // 1001 0011
int b = 61; // 0011 1101
printf("%d\n",a | b);
system("pause");
return 0;
}
// output:
// 191 (1011 1111)
~按位取反
一元运算符~把1变为0,把0变为1。
值得注意的是,~运算符并不会改变操作数的值。
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
/*
~1 = 0
~0 = 1
*/
int main(void){
unsigned char a = 15; // 0000 1111
unsigned char b = ~a; // 1111 0000
int c = 16; // 0001 0000
int d = ~c; // 1110 1111
printf("%d,%d,%d,%d",a,b,c,d);
system("pause");
return 0;
}
// output:
// 15,240,16,-17
^按位异或
对于每个位,如果两个运算对象中相应的位一个为1(但不是2个为1),结果为1。
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
/*
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
1 ^ 1 = 0
*/
int main(void){
int a = 15; // 0000 1111
int b = 240; // 1111 0000
printf("%d",a^b);
system("pause");
return 0;
}
// output:
// 255 (1111 1111)
<<左移
左移运算符(<<)将其左侧运算对象每一位的值向左移动其右侧运算对象指定的位数。左侧运算对象指定的位数。左侧运算对象移出左末端位的值丢失,用0填充空出的位置。下面的例子中,每一位向左移动其右侧运算对象给定值的位数。如下例:
(10001010) << 2 // 表达式
(00010100) // 结果值
该操作产生了一个新的位值,但是不改变其运算对象。例如,假设num = 1,那么num << 2 = 4,但是num本身不变,仍为1。可以使用左移赋值运算符(<<=)来更改变量的值。该运算符将变量中位向左移动其右侧运算对象给定值的位数。
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
int main(void){
int num = 1;
int num_1;
num_1 = num << 2; // num_1 = 4;
num <<= 2;
printf("%d,%d",num_1,num);
system("pause");
return 0;
}
// output:
// 4,4
左移注意数据溢出:
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
int main()
{
unsigned char ch = 1; // 0000 0001
printf("%d\n", ch << 7); // 1000 0000
printf("%d\n", ch << 8); //1 0000 0000
ch = (ch << 8);
printf("%d\n", ch); // 数据溢出,读取不到,输出0
system("pause");
return 0;
}
// output:
// 128
// 256
// 0
>>右移
右移运算符将其左侧运算对象每一位的值向右移动其右侧运算对象指定的位数。左侧运算对象移出右末端位的值丢弃。对于无符号类型,用0填出空出的位置;对于有符号类型,其结果取决于机器。空出的位置可用0填充,或者用符号位(最左端的位)的副本填充。
// 有的机器:
(10001010) >> 2
(00100010) // 结果值
// 还有的机器:
(10001010) >> 2
(11100010) // 结果值
// 无符号值中:
(10001010) >> 2
(00100010) // 所有系统都会得到该值
// 每个位向右移动两个位置,空出的位用0填充
因此位运算可以总结为下列形式:
number << n // number乘以2的n次幂
number >> n // 若number非负,则用number除以2的n次幂