当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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大神的英文原创作品 ^。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。