移位操作符,会把左操作数的位移动右操作数指定的位数。
<< 左移
>> 右移
看下面语句:
int value = 12;
int shiftcount = 3; //移动的位数
int result = value << shiftcount; //进行移位运算Code language: JavaScript (javascript)
以上 value 的值 12,其二进制是 0000 1100。
现在向左移动 3 位,在右边补 0。
最后就变成了 0110 0000。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int value = 12;
int shiftcount = 3; //移动的位数
int result = value << shiftcount; //进行移位运算
printf("%d",result);
return 0;
}Code language: PHP (php)
右移运算符会向右移位,但它比左移复杂一些。
对于不带符号的数值,向右移位时,会在左边的空位补 0。
下面看一些例子:
unsigned int value = 65372U;
它在二进制是:
1111 1111 0101 1100
假定现在执行如下语句:
unsigned int result = value >> 2;
向右移动两位,在左边补 0。
最后就变成了:
0011 1111 1101 0111
也就是十进制是 16343。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
unsigned int value = 65372U; //1111 1111 0101 1100
unsigned int result = value >> 2; //0011 1111 1101 0111
printf("%d",result);
return 0;
}Code language: PHP (php)
对于带符号的负值,其最左一位是 1,则移位的结果取决于系统。
大多数情况向右移动时补 1,但一些系统补 0。
比如:
int new_value = -164;
对应的二进制 1111 1111 0101 1100。
int new_result = new_value >> 2;
最后变成了 1111 1111 1101 0111。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int new_value = -164; //1111 1111 0101 1100
int new_result = new_value >> 2; //1111 1111 1101 0111
printf("%d",new_result);
return 0;
}Code language: PHP (php)