Sei sulla pagina 1di 3

Bitwise Operators El operador de desplazamiento a la derecha y el

Operators that work on the individual bits operador de desplazamiento a la izquierda también son
within a variable are called bitwise operators. operadores binarios. Aquí, los tipos de los operandos no
Following is a table of all of these operators: tienen que ser iguales. La expresión x >> 3 hace que la
& bitwise AND           >> right shift variable x se desplace hacia la derecha por tres bits
| bitwise Inclusive OR     << left shift
antes de su uso. Del mismo modo, y << 5
^  bitwise Exclusive OR           ~  one’s
will cause y to be shifted to the left by five
complement
Los operadores binarios (bit a bit)
bits. In all number systems, a left shift by
Los operadores que trabajan en los bits individuales
one digit corresponds to a multiplication by
dentro de un variable se llaman operadores bit a bit. Lo
the number base. Similarly, a shift to the
que sigue es una tabla todos los operadores:
right by one digit causes a division by the
& binario AND >> desplazamiento a la derecha
number base.
Hará que “y” se va a desplazar a la izquierda por cinco
| binario Inclusiva OR << desplazamiento a la izquierda
bits. En todos los sistemas numéricos, un desplazamiento
^ binario Exclusiva OR ~ Complemento a uno
The first three bitwise operators are traditional a la izquierda en un dígito corresponde a una
binary operators. These binary operators multiplicación por la base numérica. Del mismo modo, un
operate in integer type (char, int, long, etc.) cambio hacia la derecha en un dígito provoca una división
operands, and the two operands must be of the por la base numérica.
same type. We are using the binary system in this
Los tres primeros operadores binarios (bit a bit) son los case, so a shift left by one bit causes the
tradicionales operadores binarios actúan en el tipo number to be multiplied by two. Unlike
entero (char, int, long, etc.) operandos, y los dos most number systems, the binary system
operandos deben ser del mismo tipo. (or two’s complement system) allows the
If a bitwise AND is executed, those locations in sign of the number to be contained in the
the result where both operands have bit values binary representation of the number itself.
of 1 will have a value of 1. All other locations Estamos utilizando el sistema binario, en este caso, por
will be 0. For a bitwise inclusive OR, each bit lo que un desplazamiento a la izquierda en un bit hace
in the result will be 1 when either or both que el número debe multiplicarse por dos. A diferencia
operand bits are 1. All locations where both de la mayoría de los sistemas numéricos, el sistema
operand bits are 0 will be 0. The exclusive OR
binario (o sistema de complemento a dos) permite que el
is similar to an addition with no carry.
signo de la cantidad del número que debe figurar en la
Whenever the bits in the operands are
different, the result bit will be 1. If both representación binaria del número en sí.
operand bits are the same, either both bits 1 or These considerations lead to two different
both bits 0, the result will be 0. types of shifts for a system of binary
Si el binario (AND) se ejecuta, los lugares en el numbers. A shift in which bits vacated by
resultado de ambos operandos tienen valores de bit de the shift are replaced by zeros is called a
“1” tendrán un valor de “1”. Todas las demás lugares logical shift. All left shifts are logical shifts.
serán “0”. Para un binario OR inclusivo, cada bit en el As the shift progresses toward the left, bits
resultado será “1” cuando uno o ambos bits de operando that fill the number from the right will all be
son: “1”. Todos los lugares en los que los dos bits zero. Bits that shift out of the number on
operandos son “0” será “0”. La OR exclusiva es similar a the left side are lost. A right shift can be
una suma sin acarreo. Siempre que los bits de los either a logical or an arithmetic shift.
operandos son diferentes, el resultado del bit será “1”. Estas consideraciones conducen a dos tipos diferentes
Si ambos operandos los bits son iguales, ya sea ambos de cambios para un sistema de números binarios. Un
bits “1” o ambos bits “0”, el resultado será “0”. cambio en el que los bits vacantes por el desplazamiento
The right shift operator and the left shift se sustituyen por ceros se llama un cambio lógico. Todos
operator are also binary operators. Here los desplazamientos a la izquierda son los cambios
the types of the operands need not be the lógicos. A medida que el cambio avanza hacia la
same. The expression x >> 3 causes the izquierda, los bits que llenan el número de la derecha
variable x to be shifted to the right by three serán todos cero. Los bits que se desplazan fuera de la
bits prior to its use. Likewise, y << 5 serie en el lado izquierdo se pierden. Un desplazamiento
a la derecha puede ser un lógico o un desplazamiento En este caso, el número 7 tiene cada uno de los bits
aritmético. menos significativos encendidos o 1. Por lo tanto, el
If the type being shifted is signed, the sign término ~ 7 tiene todos los bits en el número, pero el
bit—which is the leftmost bit—will menos significativo encendido y estos tres bits están
propagate, retaining a number of the same apagado o 0. Cuando esta máscara es agregado con r,
sign. This is an arithmetic sign. If the todos los bits de r, con la excepción de los tres bits
number being shifted is unsigned, zeros are menos significativos, se terminara con un 1, y estos
filled into the number from the left as the valores de bit se mantendrá sin cambios. Los menos
shift proceeds. In all cases, bits shifted out significativos tres bits se asocian con un AND con 0 y el
of a number by a shift operation will be resultado en estos tres bits serán 0. El binario OR
lost. The one’s complement operator ~ is a encenderán los bits. Suponga que desea encender los
unary operator that causes the bits in a bits 2 y 3 de r por encima de. Aquí deberá usar r = r |
variable to be reversed. Every 1 is replaced 0x0c;
by a 0, and every 0 is The hexadecimal number 0x0c is a number
replaced by a 1. The bitwise AND  and OR that has bits 2 and 3 turned on and all
operations are used to turn bits on and off. other bits turned off. This OR operation will
Suppose that we have a character variable leave bits 2 and 3 on and all other bits will
r, and we wish to turn the least significant remain unchanged. Suppose that you want
three bits off. Try to complement a bit in a variable. For
Si se firma el tipo se desplace, el signo de bits que es la example, bit 0 of the memory location
más a la izquierda de bits se propague, conservando un PORTA must be toggled each time a certain
número del mismo signo. Este es un signo aritmético. Si routine is entered. The expression
el número se desplace está sin firmar, los ceros se PORTA = PORTA ^ 1;
introducen en el número de la izquierda a medida que El número hexadecimal 0x0c es un número que tiene los
avanza por turnos. En todos los casos, bits desplazados bits 2 y 3 encendidos y todos los demás bits apagados.
fuera de un número por una operación de cambio se Esta operación (OR) dejará los bits 2 y 3 y todos los
perderá. Operador complementario de uno ~ es un demás bits se mantendrá sin cambios. Suponga que usted
operador unario que hace que los bits en una variable desea complementar un bit en una variable. Por ejemplo,
para ser invertidos. Cada 1 se sustituye por un “0”, y el bit 0 de la posición de memoria PORTA debe ser
cada 0 es reemplazado por un 1. El operador AND y OR fijada cada vez que se introduce una cierta rutina. La
se utilizan para activar y desactivar los bits. expresión PORTA = PORTA ^ 1;
Supongamos que tenemos una variable de carácter r, y will perform this operation. All of the bits
queremos volver los menos significativos tres bits except for bit 1 of PORTA  will remain
apagado. intentar unchanged because the exclusive OR  of
In this case, the number 7 has each of the any bit with a 0  will not change the bit
least significant bits turned on or 1. value. However, if bit 1 is 1 in PORTA  the
Therefore, the term ~7 has all of the bits in exclusive OR  will force this bit to 0. If this
the number but the least significant turned bit is 0, the exclusive OR  will force this bit
on and these three bits are turned off or 0. to a 1. Therefore, the above expression will
When this mask is ANDed with r, all of the complement bit 0 of PORTA each time it is
bits of r,  with the exception of the least executed. 
significant three bits, will be ANDed with a llevará a cabo esta operación. Todos los bits excepto el
1, and these bit values will remain bit 1 del PORTA permanecerán sin cambios debido a que
unchanged. The least significant three bits el OR exclusivo de cualquier bit con un 0 no va a cambiar
will be ANDed with 0 and the result in these el valor del bit. Sin embargo, si el bit 1 es 1 en PORTA la
three bits will OR exclusiva forzará este bit a 0. Si este bit es 0, la OR
be 0. The bitwise OR will turn bits on. exclusiva obligará este bit a un 1. Por lo tanto, la
Suppose you wanted to turn bits 2 and 3 of expresión anterior complementará el bit 0 del PORTA
r  above on. Here you would use r = r | cada vez que se ejecuta.
0x0c; The bitwise operators &, |,  and ^  are of
lower precedence than the equality
operators, and higher precedence than the
logical AND operator. The bit shift operators
are of the same precedence, of lower
precedence than the arithmetic operators +
and ­ , and of higher precedence than the
relational operators.
Los operadores de bits &, | y ,^ son de menor
precedencia que los operadores de igualdad y
mayor precedencia que el operador lógico
AND. Los operadores de desplazamiento de bits
tienen la misma prioridad, de menor
precedencia que los operadores aritméticos +
y -, y de mayor precedencia que los operadores
relacionales.

Potrebbero piacerti anche