左移,右移

從 YFRobotwiki
在2017年9月10日 (日) 15:59由Allblue對話 | 貢獻所做的修訂版本

跳到: 導覽搜尋

描述

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論壇