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


Arduino |用法及代码示例


[位运算符]

说明

C++ 中的按位或运算符是竖线符号 |。与 & 运算符一样,|在其周围的两个整数表达式中独立地操作每个位,但它的作用是不同的(当然)。如果两个输入位中的一个或两个为 1,则两个位的按位或为 1,否则为 0。

换句话说:

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

示例代码

int a =  92;    // in binary: 0000000001011100
int b = 101;    // in binary: 0000000001100101
int c = a | b;  // result:    0000000001111101, or 125 in decimal.

按位或最常见的用途之一是在 bit-packed 数字中设置多个位。

// Note: This code is AVR architecture specific
// set direction bits for pins 2 to 7, leave PD0 and PD1 untouched (xx | 00 == xx)
// same as pinMode(pin, OUTPUT) for pins 2 to 7 on Uno or Nano
DDRD = DDRD | 0b11111100;

相关用法


注:本文由纯净天空筛选整理自arduino.cc大神的英文原创作品 |。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。