左移,右移

来自YFRobotwiki
2017年9月10日 (日) 15:59Allblue讨论 | 贡献的版本

跳转至: 导航搜索

描述

From The Bitmath Tutorial in The Playground

There are two bit shift operators in C++: the left shift operator << and the right shift operator >>. These operators cause the bits in the left operand to be shifted left or right by the number of positions specified by the right operand.

More on bitwise math may be found here.

描述


描述

在C++中有两个移位运算符:左移运算符(<<)和右移运算符(>>)。可实现让操作数的每位实现左移或者右移。更多位运算可,点击这里


语法 variable << number_of_bits
variable >> number_of_bits


参数

variable: byte, int, long型变量
number_of_bits: 需要移动的位数,最大不超过32。


示例

int a = 5;        // 二进制: 0000000000000101
int b = a << 3;   // 二进制: 0000000000101000, 或者 4(十进制)
int c = b >> 3;   // 二进制: 0000000000000101, 或者说回到原始值5


注意事项

当把x左移y位(x << y),x中最左边的y位将会丢失。

int a = 5;        // 二进制: 0000000000000101
int b = a << 14;  // 二进制: 0100000000000000 - 101中的第一个1被丢弃

如果你想确保位移不会引起数据溢出,可以简单的把左移运算当做对左运算元进行2的右运算元次方的操作。例如,要产生2的次方,可使用下面的方式:

1 <<  0  ==    1
1 <<  1  ==    2
1 <<  2  ==    4
1 <<  3  ==    8
  ...
1 <<  8  ==  256
1 <<  9  ==  512
1 << 10  == 1024
  ...

当把x右移y位,x的最高位为1,位移结果由x的数据类型决定。正如我们在上面已经讨论过的,如果x是int型,那么最高位为符号位,用来决定x是否为负数。在这种情况下,符号位被复制到较低位:

int x = -16;     // 二进制: 1111111111110000
int y = x >> 3;  // 二进制: 1111111111111110

这种情况被称为符号扩展,也往往不是你想要的结果。相反,你可能希望移入左边的是0。而事实上右移规则对于无符号整型是有所不同的。你可以通过数据强制转换改变从左边移入的数据。

int x = -16;                   // 二进制: 1111111111110000
int y = (unsigned int)x >> 3;  // 二进制: 0001111111111110

如果你想避免符号扩展的话,建议你可以使用右移位运算符>>,作为除以2的幂的方法。例如:

int x = 1000;
int y = x >> 3;   // 1000除以8,得y = 125.




返回Arduino语法参考列表

更多建议和问题欢迎反馈至 YFRobot论坛