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


Arduino ^用法及代碼示例

[位運算符]

說明

C++ 中有一個有點不尋常的運算符,稱為按位異或,也稱為按位異或。 (在英語中,這通常發音為 "eks-or"。)按位 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)整數表達式中的某些位。在按位異或運算中,如果掩碼位中有 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);
}

相關用法


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