當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Arduino <<用法及代碼示例

[位運算符]

說明

左移運算符<< 使左操作數的位左移右操作數指定的位置數。

用法

variable << number_of_bits;

參數

variable:允許的數據類型:byte,int,long.
number_of_bits: < = 32 的數字。允許的數據類型:int.

示例代碼

int a = 5;      // binary: 0000000000000101
int b = a << 3; // binary: 0000000000101000, or 40 in decimal

注意事項和警告

當您將值 x 移動 y 位 (x << y) 時,x 中最左邊的 y 位將丟失,字麵意思是移出不存在:

int x = 5;  // binary: 0000000000000101
int y = 14;
int result = x << y;  // binary: 0100000000000000 - the first 1 in 101 was discarded

如果您確定一個值中的任何一個都沒有被轉移到遺忘中,那麽考慮 left-shift 運算符的一種簡單方法是,它將左操作數乘以 2 的右操作數冪。例如,要生成 2 的冪,可以使用以下表達式:

   Operation  Result
   ---------  ------
    1 <<  0      1
    1 <<  1      2
    1 <<  2      4
    1 <<  3      8
    ...
    1 <<  8    256
    1 <<  9    512
    1 << 10   1024
    ...

以下示例可用於將接收到的字節的值打印到串行監視器,使用左移運算符將字節從底部(LSB)移動到頂部(MSB),並打印出其二進製值:

// Prints out Binary value (1 or 0) of byte
void printOut1(int c) {
  for (int bits = 7; bits > -1; bits--) {
    // Compare bits 7-0 in byte
    if (c & (1 << bits)) {
      Serial.print("1");
    }
    else {
      Serial.print("0");
    }
  }
}

相關用法


注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 <<。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。