^ (bitwise xor)

解説

C++にはbitwise EXCLUSIVE OR(bitwise XORとも呼ばれています)は、ビットごとのXOR演算子を、キャレット記号^を使って記述します。
ビットごとのXOR演算は、入力ビットが異なる場合にのみ1を返しそうでない場合は0を返します。

0  0  1  1    operand1
0  1  0  1    operand2
----------
0  1  1  0    (operand1 ^ operand2) - returned result

コード例

int x = 12;     // binary: 1100
int y = 10;     // binary: 1010
int z = x ^ y;  // binary: 0110, or decimal 6

整数式の一部のビットをトグル(0から1、1から0に)するために、^演算子がよく使われます。
ビットごとのXOR演算では、マスクビットに1があれば、そのビットは反転し、0があればそのビットは反転せずそのままの状態になります。

// Note: This code uses registers specific to AVR microcontrollers (Uno, Nano, Leonardo, Mega, etc.)
// it will not compile for other architectures
void setup() {
  DDRB = DDRB | 0b00100000;  // set PB5 (pin 13 on Uno/Nano, pin 9 on Leonardo/Micro, pin 11 on Mega) as OUTPUT
  Serial.begin(9600);
}

void loop() {
  PORTB = PORTB ^ 0b00100000;  // invert PB5, leave others untouched
  delay(100);
}
タイトルとURLをコピーしました