< <

[Bitwise Operators]

説明

The left shift operator << causes the bits of the left operand to be shifted left by the number of positions specified by the right operand.

構文

variable << number_of_bits;

媒介変数

variable: 許可されるデータ型: byteintlong.
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

値内の1が全てシフトされて消えてしまうことがないと確信できる場合、左シフト演算子は左オペランドに右オペランドの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");
    }
  }
}

参照

  • [Example] BitMath Tutorial

Language Reference Home

86Duino のリファレンスのテキストは Arduino レファレンス を編集したもので、 Creative Commons Attribution-ShareAlike 3.0 License下でライセンスされています。リファレンス内のコードサンプルはパブリックドメインとして公開されています。

上部へスクロール