^(ビット単位の排他OR演算子)

Last revision:2024/05/21

名称

^(ビット単位の排他OR演算子)

説明

ビット単位の排他OR演算子という耳慣れない演算子がC++にはある。ビット単位の排他OR演算子は、^で表す。ビット単位の排他OR演算子は、それぞれのビットが異なれば1で、同じであれば0である。

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

使用例

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

ビット単位の排他OR演算子は、整数式の特定のビットを反転(0を1に、1を0にする)するときによく使われる。ビット単位の排他OR演算子を使うと、マスクビットが1のときは反転し、0のときはそのままである。以下の例は、PB5番を点滅させる。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 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);
}

参照

オリジナルのページ

https://docs.arduino.cc/language-reference/en/structure/bitwise-operators/bitwiseXor/

最終更新日

July 22, 2026

inserted by FC2 system