Reference.BitwiseAnd History

Hide minor edits - Show changes to markup

June 02, 2010, at 04:21 PM by Equipo Traduccion -
Changed lines 1-16 from:

Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^)

Bitwise AND (&)

The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming problems. Much of the material below is from an excellent tutorial on bitwise math wihch may be found here.

Description and Syntax

Below are descriptions and syntax for all of the operators. Further details may be found in the referenced tutorial.

Bitwise AND (&)

The bitwise AND operator in C++ is a single ampersand, &, used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0. Another way of expressing this is:

    0  0  1  1    operand1
    0  1  0  1    operand2
to:

Operadores bit a bit: AND (&), OR (|) y XOR (^)

Los operadores bit a bit realizan sus cálculos a nivel de los bits de las variables. Ayudan a resolver muchos de los problemas más comunes a nivel de programación. La mayoría del material que sigue está sacado de un excelente tutorial de matemática lógica, que puede ser encontrado aquí.

Descripción y sintaxis

A continuación se muestras las descripciones y la sintaxis de estos operadores lógicos. Puedes encontrar más información sobre ellos en el tutorial enlazado sobre estas líneas.

Operador bit a bit AND (&)

Este operador, en C++, es un ampersand (&) simple, usado entre dos expresiones enteras. Opera en cada posición de bit en ambas expresiones de forma independiente, de acuerdo a esta regla: si ambas posiciones de entrada son un 1, el resultado devuelto es un 1; en otro caso, será un 0. Por ejemplo:

[@

    0  0  1  1    operando1
    0  1  0  1    operando2
Changed lines 17-35 from:
    0  0  0  1    (operand1 & operand2) - returned result

In Arduino, the type int is a 16-bit value, so using & between two int expressions causes 16 simultaneous AND operations to occur. In a code fragment like:

    int a =  92;    // in binary: 0000000001011100
    int b = 101;    // in binary: 0000000001100101
    int c = a & b;  // result:    0000000001000100, or 68 in decimal.

Each of the 16 bits in a and b are processed by using the bitwise AND, and all 16 resulting bits are stored in c, resulting in the value 01000100 in binary, which is 68 in decimal.

One of the most common uses of bitwise AND is to select a particular bit (or bits) from an integer value, often called masking. See below for an example

Bitwise OR (|)

The bitwise OR operator in C++ is the vertical bar symbol, |. Like the & operator, | operates independently each bit in its two surrounding integer expressions, but what it does is different (of course). The bitwise OR of two bits is 1 if either or both of the input bits is 1, otherwise it is 0. In other words:

    0  0  1  1    operand1
    0  1  0  1    operand2
to:
    0  0  0  1    (operando1 & operando2) - resultado devuelto

@]

En Arduino, el tipo entero (int) ocupa 16bits, pero usando & entre dos expresiones tipo int, causa 16 operaciones AND simultáneas. En el siguiente código:

    int a =  92;    // en binario: 0000000001011100
    int b = 101;    // en binario: 0000000001100101
    int c = a & b;  // resultado:    0000000001000100, 68 en decimal.

Cada uno de los 16bits de las palabras a y b son procesados usando el operador bit a bit AND y se guarda el resultado en la palabra c.

Uno de los usos más comunes de este operador es seleccionar un determinado (o determinados) bits dentro de un valor entero, también llamado enmascaramiento (masking). Más abajo se incluye un ejemplo.

Operador bit a bit OR (|)

Este operador, en C++, se simboliza como una barra vertical, |. Como el operador AND, este operador trabaja de forma de forma independiente cada pareja de bits. Sin embargo, lo que hace (lógicamente) es diferente: el operador OR devuelve un 1, si alguno (o los dos bits) es un 1; mientras que sólo devuelve un 0 si ambos bits lo son. En otras palabras:

[@

    0  0  1  1    operando1
    0  1  0  1    operando2
Changed lines 41-60 from:
    0  1  1  1    (operand1 | operand2) - returned result

Here is an example of the bitwise OR used in a snippet of C++ code:

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

Example Program

A common job for the bitwise AND and OR operators is what programmers call Read-Modify-Write on a port. On microcontrollers, a port is an 8 bit number that represents something about the condition of the pins. Writing to a port controls all of the pins at once.

PORTD is a built-in constant that refers to the output states of digital pins 0,1,2,3,4,5,6,7. If there is 1 in an bit position, then that pin is HIGH. (The pins already need to be set to outputs with the pinMode() command.) So if we write PORTD = B00110001; we have made pins 2,3 & 7 HIGH. One slight hitch here is that we may also have changeed the state of Pins 0 & 1, which are used by the Arduino for serial communications so we may have interfered with serial communication.

     Our algorithm for the program is:
  • Get PORTD and clear out only the bits corresponding to the pins we wish to control (with bitwise AND).
  • Combine the modified PORTD value with the new value for the pins under control (with biwise OR).

[@int i; // counter variable

to:
    0  1  1  1    (operando1 | operando2) - valor devuelto

@]

A continuación un ejemplo de uso de este operador:

    int a =  92;    // en binario: 0000000001011100
    int b = 101;    // en binario: 0000000001100101
    int c = a | b;  // resultado:    0000000001111101, 125 en decimal.

Programa de ejemplo

Un trabajo común de los operadores vistos hasta ahora es leer-modificar-escribir en un puerto. En los microcontroladores, un puerto es un número de 8bits que representa la condición (estado) de cada pin. Escribir en un puerto controla todos los pines de ese puerto a la vez.

PORTD es una constante definida para referirse a los estados de salida de los pines digitales 0, 1, 2, 3, 4, 5, 6 y 7. Si hay un 1 en una determinada posición, ese pin se encuentra a nivel alto (HIGH). (Los pines necesitan estar declarados como salida usando la instrucción pinMode). Entonces, si escribimos PORTD = B00010100;, pondremos los pines 2 y 4 a nivel alto. Un ligero problema es que, al asignarle un valor al puerto directamente, se puede modificar el valor de otro pin, por ejemplo, el valor del bit 0 y 1 del puerto D, usados por el Arduino en comunicaciones serie, por lo que podríamos estar interfiriendo en esa comunicación.

Explicado esto, el algoritmo del programa de ejemplo es:

  • Leer el valor actual del puerto y borrar sólo los bits correspondientes con los pines que queremos controlar (operador AND).
  • Combinar el valor modificado del puerto con el valor real del puerto, para que se reflejen los cambios en los bits que controlamos (operador OR).

[@int i; // variable de contador

Changed lines 67-69 from:

DDRD = DDRD | B11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx) // same as pinMode(pin, OUTPUT) for pins 2 to 7 Serial.begin(9600);

to:
    DDRD = DDRD | B11111100; // configura los bits (pines) a 1 como salida, sin tocar el 0 y el 1
              // es lo mismo que hacer pinMode(pin, OUTPUT), pero de una sola vez.
    Serial.begin(9600);
Changed lines 73-79 from:

for (i=0; i<64; i++){

PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 and 1 untouched (xx & 11 == xx) j = (i << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1 PORTD = PORTD | j; // combine the port information with the new information for LED pins Serial.println(PORTD, BIN); // debug to show masking delay(100);

to:
   for (i=0; i<64; i++){

       PORTD = PORTD & B00000011;  // borra todos los bits excepto los dos primeros, 0 y 1.
       j = (i << 2);               // desplaza dos posiciones la variable, introduciendo 0 por la derecha,
                                         // para no interferir con el valor de esos pines
       PORTD = PORTD | j;          // combina la información del puerto con la nueva para los pines del LED
      Serial.println(PORTD, BIN); // sirve para comprobar la máscara
      delay(100);
Changed lines 85-90 from:

Bitwise XOR (^)

There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^. This operator is very similar to the bitwise OR operator |, only it evaluates to 0 for a given bit position when both of the input bits for that position are 1:

    0  0  1  1    operand1
    0  1  0  1    operand2
to:

Operador bit a bit XOR (^)

Este es un operador poco usado en C++, llamado o-exlcusiva (X-OR). Este operador es escrito usando el caracter ^. Es similar al operador or (|), pero sólo devuelve un 1 cuando los bits son diferentes; devolviendo 0 en el resto de los casos. Por ejemplo:

[@ 0 0 1 1 operando1

    0  1  0  1    operando2
Changed lines 92-103 from:
    0  1  1  0    (operand1 ^ operand2) - returned result

Another way to look at bitwise XOR is that each bit in the result is a 1 if the input bits are different, or 0 if they are the same.

Here is a simple code example:

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

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise OR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. Below is a program to blink digital pin 5.

to:
    0  1  1  0    (operando1 ^ operando2) - valor devuelto

@]

A continuación un pequeño código de ejemplo:

Added lines 98-105:
    int x = 12;     // binario: 1100
    int y = 10;     // binario: 1010
    int z = x ^ y;  // binario: 0110, 6 en decimal

@]

Este operador se suele usar para invertir (cambiar 0s a 1, o viceversa, también llamado toggle), algunos (o todos) bits de una expresión. Siempre que una posición de la máscara esté a 1, esa posición será invertida en la palabra de entrada. Si hay un 0 en la máscara, esa posición no se verá afectada. A continuación un ejemplo para hacer parpadear un LED en la salida digital 5.

[@

Changed line 107 from:

// demo for Exclusive OR

to:

// ejemplo de OR exclusiva

Changed lines 109-110 from:

DDRD = DDRD | B00100000; // set digital pin five as OUTPUT Serial.begin(9600);

to:
   DDRD = DDRD | B00100000; // pin 5 configurado como salida, pinMode(5, OUTPUT);
   Serial.begin(9600);
Changed lines 114-115 from:

PORTD = PORTD ^ B00100000; // invert bit 5 (digital pin 5), leave others untouched delay(100);

to:
   PORTD = PORTD ^ B00100000;  // invierte el bit 5 (pin digital 5) y los no modifica el resto
   delay(100);
Changed lines 119-121 from:

See Also

  • &&(Boolean AND)
  • ||(Boolean OR)
to:

Ver también

  • &&(AND booleana)
  • ||(OR booleana)
June 10, 2007, at 08:15 PM by Paul Badger -
Changed lines 80-81 from:

There is a somewhat unusual operator in C++ called bitwise exclusive OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^. This operator is very similar to the bitwise OR operator |, only it evaluates to 0 for a given bit position when both of the input bits for that position are 1:

to:

There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^. This operator is very similar to the bitwise OR operator |, only it evaluates to 0 for a given bit position when both of the input bits for that position are 1:

June 10, 2007, at 08:12 PM by Paul Badger -
Changed lines 95-96 from:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. Below is a program to blink digital pin 5.

to:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise OR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. Below is a program to blink digital pin 5.

April 24, 2007, at 12:30 AM by Paul Badger -
Deleted line 106:

// all others unchanged

April 24, 2007, at 12:29 AM by Paul Badger -
Deleted line 99:
Changed line 106 from:

PORTD = PORTD & B00100000; // invert bit 5 (digital pin 5)

to:

PORTD = PORTD ^ B00100000; // invert bit 5 (digital pin 5), leave others untouched

Deleted line 108:
   }
April 24, 2007, at 12:26 AM by Paul Badger -
Changed line 61 from:

DDRD = DDRD | 11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx)

to:

DDRD = DDRD | B11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx)

Changed lines 95-98 from:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. For example:

    y = x ^ B00000001;   // toggle the lowest bit in x, and store the result in y.
to:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. Below is a program to blink digital pin 5.

// Blink_Pin_5
// demo for Exclusive OR

void setup(){
DDRD = DDRD | B00100000; // set digital pin five as OUTPUT 
Serial.begin(9600);
}

void loop(){
PORTD = PORTD & B00100000;  // invert bit 5 (digital pin 5)
// all others unchanged 
delay(100);
   }
}

April 24, 2007, at 12:16 AM by Paul Badger -
Changed line 61 from:

DDRD = DDRD | 11111100; // set direction bits for pins 2 to 7, leave 0 & 1 untouched (xx | 00 == xx)

to:

DDRD = DDRD | 11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx)

Deleted line 63:

Serial.println("start");

Changed lines 69-70 from:

PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 & 1 untouched (xx & 11 == xx) j = (i << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 & 1

to:

PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 and 1 untouched (xx & 11 == xx) j = (i << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1

April 24, 2007, at 12:14 AM by Paul Badger -
Changed lines 57-62 from:

[@// program to demonstrate writing to ports & bitmasking // Paul Badger 2007 // set some LED's (w. series resistors) up on pins 2 to 7 // and watch the program count in binary

int i; // counter variable

to:

[@int i; // counter variable

Changed line 61 from:

DDRD = DDRD & 11111100; // set direction bits for pins 2 to 7

to:

DDRD = DDRD | 11111100; // set direction bits for pins 2 to 7, leave 0 & 1 untouched (xx | 00 == xx)

Added lines 63-64:

Serial.begin(9600); Serial.println("start");

Changed line 67 from:

void loop{

to:

void loop(){

Changed lines 70-72 from:

PORTD = PORTD & B00000011; // mask out bits 2 - 7

to:

PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 & 1 untouched (xx & 11 == xx) j = (i << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 & 1 PORTD = PORTD | j; // combine the port information with the new information for LED pins

Changed lines 74-76 from:

j = (i << 2); // shift variable up to pins 2 - 7 PORTD = PORTD | j; // combine the port information with the new information for LED pins Serial.println(PORTD, BIN); // debug to show masking

to:

delay(100);

Changed lines 76-78 from:

} @]

to:

}@]

April 18, 2007, at 03:47 PM by Paul Badger -
Changed lines 99-100 from:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. For example:

to:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. For example:

April 18, 2007, at 03:43 PM by Paul Badger -
Changed line 15 from:
    1  1  0  0    operand1
to:
    0  0  1  1    operand1
Changed lines 18-19 from:
    0  1  0  0    (operand1 & operand2) - returned result
to:
    0  0  0  1    (operand1 & operand2) - returned result
Changed line 35 from:
    1  1  0  0    operand1
to:
    0  0  1  1    operand1
Changed lines 38-39 from:
    1  1  0  1    (operand1 | operand2) - returned result
to:
    0  1  1  1    (operand1 | operand2) - returned result
Changed line 86 from:
    1  1  0  0    operand1
to:
    0  0  1  1    operand1
Changed lines 89-90 from:
    1  0  0  1    (operand1 ^ operand2) - returned result
to:
    0  1  1  0    (operand1 ^ operand2) - returned result
April 18, 2007, at 03:40 PM by Paul Badger -
Changed lines 1-2 from:

Bitwise AND (&), Bitwise OR (|)

to:

Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^)

Changed lines 99-100 from:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is 1 in the mask bit, that bit is inverted, if there is a 0, the bit is not inverted and stays the same. For example:

to:

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. For example:

April 18, 2007, at 03:35 PM by Paul Badger -
Added lines 81-102:

Bitwise XOR (^)

There is a somewhat unusual operator in C++ called bitwise exclusive OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^. This operator is very similar to the bitwise OR operator |, only it evaluates to 0 for a given bit position when both of the input bits for that position are 1:

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

Another way to look at bitwise XOR is that each bit in the result is a 1 if the input bits are different, or 0 if they are the same.

Here is a simple code example:

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

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise NOR operation if there is 1 in the mask bit, that bit is inverted, if there is a 0, the bit is not inverted and stays the same. For example:

    y = x ^ B00000001;   // toggle the lowest bit in x, and store the result in y.
April 18, 2007, at 03:46 AM by Paul Badger -
Changed line 83 from:
  • |(Boolean OR)
to:
  • ||(Boolean OR)
April 18, 2007, at 03:46 AM by Paul Badger -
Changed lines 79-80 from:

}

to:

} @]

April 18, 2007, at 03:45 AM by Paul Badger -
Added lines 46-47:

Example Program

April 18, 2007, at 03:43 AM by Paul Badger -
Changed lines 80-81 from:
  • &&?(Boolean AND)
  • (Boolean OR)
to:
  • &&(Boolean AND)
  • |(Boolean OR)
April 18, 2007, at 03:41 AM by Paul Badger -
April 18, 2007, at 03:41 AM by Paul Badger -
Changed lines 80-81 from:

&&?(Boolean AND) (Boolean OR)

to:
  • &&?(Boolean AND)
  • (Boolean OR)
April 18, 2007, at 03:40 AM by Paul Badger -
Changed lines 1-2 from:

Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), Bitwise NOT (~)

to:

Bitwise AND (&), Bitwise OR (|)

Bitwise AND (&)

Added lines 79-81:

See Also &&?(Boolean AND) (Boolean OR)

April 18, 2007, at 03:37 AM by Paul Badger -
Added lines 1-76:

Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), Bitwise NOT (~)

The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming problems. Much of the material below is from an excellent tutorial on bitwise math wihch may be found here.

Description and Syntax

Below are descriptions and syntax for all of the operators. Further details may be found in the referenced tutorial.

Bitwise AND (&)

The bitwise AND operator in C++ is a single ampersand, &, used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0. Another way of expressing this is:

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

In Arduino, the type int is a 16-bit value, so using & between two int expressions causes 16 simultaneous AND operations to occur. In a code fragment like:

    int a =  92;    // in binary: 0000000001011100
    int b = 101;    // in binary: 0000000001100101
    int c = a & b;  // result:    0000000001000100, or 68 in decimal.

Each of the 16 bits in a and b are processed by using the bitwise AND, and all 16 resulting bits are stored in c, resulting in the value 01000100 in binary, which is 68 in decimal.

One of the most common uses of bitwise AND is to select a particular bit (or bits) from an integer value, often called masking. See below for an example

Bitwise OR (|)

The bitwise OR operator in C++ is the vertical bar symbol, |. Like the & operator, | operates independently each bit in its two surrounding integer expressions, but what it does is different (of course). The bitwise OR of two bits is 1 if either or both of the input bits is 1, otherwise it is 0. In other words:

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

Here is an example of the bitwise OR used in a snippet of C++ code:

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

A common job for the bitwise AND and OR operators is what programmers call Read-Modify-Write on a port. On microcontrollers, a port is an 8 bit number that represents something about the condition of the pins. Writing to a port controls all of the pins at once.

PORTD is a built-in constant that refers to the output states of digital pins 0,1,2,3,4,5,6,7. If there is 1 in an bit position, then that pin is HIGH. (The pins already need to be set to outputs with the pinMode() command.) So if we write PORTD = B00110001; we have made pins 2,3 & 7 HIGH. One slight hitch here is that we may also have changeed the state of Pins 0 & 1, which are used by the Arduino for serial communications so we may have interfered with serial communication.

     Our algorithm for the program is:
  • Get PORTD and clear out only the bits corresponding to the pins we wish to control (with bitwise AND).
  • Combine the modified PORTD value with the new value for the pins under control (with biwise OR).

[@// program to demonstrate writing to ports & bitmasking // Paul Badger 2007 // set some LED's (w. series resistors) up on pins 2 to 7 // and watch the program count in binary

int i; // counter variable int j;

void setup(){ DDRD = DDRD & 11111100; // set direction bits for pins 2 to 7 // same as pinMode(pin, OUTPUT) for pins 2 to 7 }

void loop{ for (i=0; i<64; i++){

PORTD = PORTD & B00000011; // mask out bits 2 - 7 Serial.println(PORTD, BIN); // debug to show masking j = (i << 2); // shift variable up to pins 2 - 7 PORTD = PORTD | j; // combine the port information with the new information for LED pins Serial.println(PORTD, BIN); // debug to show masking

   }

}

Share