Binary shifts and bit manipulation · Desplazamientos binarios y manipulación de bits
| English | Español |
|---|---|
| bit/bɪt/ | bit |
| mask/mæsk/ | máscara |
| logical shift/ˈlɒdʒɪkl ʃɪft/ | desplazamiento lógico |
| sign bit/saɪn bɪt/ | bit de signo |
| arithmetic right shift/ˌærɪθˈmetɪk raɪt ʃɪft/ | desplazamiento aritmético a la derecha |
| cyclic shift/ˈsaɪklɪk ʃɪft/ | desplazamiento cíclico |
Multiplying on a chip that cannot multiply
- The processor in the 1989 Game Boy had no multiply instruction at all. Every score, every coordinate that needed doubling was doubled by sliding its bits one place to the left.
- A shift takes one clock tick. Multiplication built from shifts and additions is how those games ran on a few kilobytes and a handful of milliwatts.
- The same tricks control single wires in an embedded device: one bit of a register per sensor or actuator, tested and set with a mask 掩码.
- This lesson is the three kinds of shift and the four mask operations, in the exam's own instructions.
Multiplicar en un chip que no puede multiplicar
- El procesador del Game Boy de 1989 no tenía ninguna instrucción de multiplicación. Cada puntuación, cada coordenada que necesitaba duplicarse se duplicaba desplazando sus bits una posición a la izquierda.
- Un desplazamiento toma un ciclo de reloj. La multiplicación construida a partir de desplazamientos y sumas es como funcionaban esos juegos con unos pocos kilobytes y unas cuantas milivatios.
- Los mismos trucos controlan hilos individuales en un dispositivo embebido: un bit de un registro por sensor o actuador, probado y configurado con una máscara.
- Esta lección trata los tres tipos de desplazamiento y las cuatro operaciones de máscara, según las instrucciones del examen.
Logical shifts
- A logical shift 逻辑移位 moves every bit left or right by some places and fills the vacated positions with 0.
LSL #1moves the bits left and a 0 enters on the right: for an unsigned number that is × 2.LSR #1moves them right and a 0 enters on the left: integer ÷ 2.- Shifting by $n$ places multiplies or divides by $2^{n}$.
00001011(11) afterLSL #1is00010110(22); afterLSR #1it is00000101(5, the remainder lost).
Logical left (× 2), logical right (÷ 2) and arithmetic right (keeps the sign bit)
Desplazamientos lógicos
- Un desplazamiento lógico mueve todos los bits a la izquierda o a la derecha algunos lugares y rellena las posiciones vacantes con 0.
LSL #1mueve los bits a la izquierda y entra un 0 por la derecha: para un número sin signo eso es × 2.LSR #1los mueve a la derecha y entra un 0 por la izquierda: entero ÷ 2.- Desplazar $n$ lugares multiplica o divide por $2^{n}$.
00001011(11) después deLSL #1es00010110(22); después deLSR #1es00000101(5, el resto se pierde).

Desplazamiento lógico izquierdo (× 2), lógico derecho (÷ 2) y aritmético derecho (mantiene el bit de signo)
Shift and mask the bits of a byte · Desplaza y enmascara los bits de un byte
Pick an operator and watch each result bit. A left shift (<<) moves every bit up one place (×2); a right shift (>>) moves them down (÷2); AND with a mask clears the bits you don't want. · Elige un operador y observa cada bit resultante. Un desplazamiento a la izquierda (<<) mueve cada bit una posición hacia arriba (×2); un desplazamiento a la derecha (>>) los mueve hacia abajo (÷2); AND con una máscara borra los bits que no deseas.
The 8-bit value 00001011 (11) is shifted left by 1 (LSL #1). What is the new denary value? · El valor de 8 bits 00001011 (11) se desplaza a la izquierda en 1 posición (LSL #1). ¿Cuál es el nuevo valor en base diez?
A left shift by 1 multiplies by 2: $11 \times 2 = 22$ (00010110). · Un desplazamiento a la izquierda por 1 multiplica por 2: $11 \times 2 = 22$ (00010110).
Shifting an unsigned number left by 3 places multiplies it by what number? · Desplazar un número sin signo a la izquierda 3 posiciones lo multiplica por qué número?
Shifting by $n$ places multiplies by $2^n$, so by 3 places is $2^3 = 8$. · Desplazar por $n$ posiciones multiplica por $2^n$, por lo que desplazar por 3 posiciones equivale a $2^3 = 8$.
Worked example: when × 4 stops being true
- Bits shifted off the end are lost, so the multiplication is only correct while they were zeros.
LSL #2on the two's complement byte11001010gives00101000. The two 1s that fell off the left are gone, the sign bit has changed, and the result is no longer four times the original.LSL #2on00001011(11) gives00101100(44), which is correct, because only zeros were lost.- The exam asks for both: the shifted pattern, and a comment on whether the value is still right.
Ejemplo resuelto: cuando × 4 deja de ser correcto
- Los bits desplazados hacia el final se pierden, por lo que la multiplicación solo es correcta mientras fueran ceros.
LSL #2sobre el byte en complemento a dos11001010da00101000. Los dos 1 que cayeron por la izquierda han desaparecido, el bit de signo ha cambiado y el resultado ya no es cuatro veces el original.LSL #2sobre00001011(11) da00101100(44), que es correcto, porque solo se perdieron ceros.- El examen pide ambos: el patrón desplazado y un comentario sobre si el valor sigue siendo correcto.
Arithmetic right shift
- A plain logical right shift puts a 0 in the top bit, which would turn a negative two's complement number positive.
- An arithmetic right shift 算术右移 copies the sign bit 符号位 into each vacated place, so a negative number stays negative and the shift still divides by 2.
10011110shifted arithmetically right by 3 places is11110011;01011100gives00001011.
Logical and arithmetic right shift on the same byte: only the entering bit differs
Desplazamiento aritmético a la derecha
- Un simple desplazamiento lógico a la derecha pone un 0 en el bit más significativo, lo que convertiría un número en complemento a dos negativo en positivo.
- Un desplazamiento aritmético a la derecha copia el bit de signo en cada lugar vacío, por lo que un número negativo permanece negativo y el desplazamiento todavía divide por 2.
10011110desplazado aritméticamente a la derecha 3 lugares es11110011;01011100da00001011.

Desplazamiento lógico y aritmético a la derecha en el mismo byte: solo difiere el bit de entrada
An arithmetic right shift differs from a logical right shift because it: · Un desplazamiento aritmético a la derecha difiere de un desplazamiento lógico a la derecha porque:
It preserves the sign bit, so dividing a negative signed number by a power of 2 keeps it negative. · Preserva el bit de signo, por lo que dividir un número firmado negativo por una potencia de 2 lo mantiene negativo.
A logical right shift always puts a 0 in the top bit, so it can turn a negative signed number positive. · Un desplazamiento lógico a la derecha siempre coloca un 0 en el bit más significativo, por lo que puede convertir un número firmado negativo en positivo.
That is exactly why signed division needs an arithmetic right shift, which copies the sign bit instead. · Esa es exactamente la razón por la que la división firmada necesita un desplazamiento aritmético a la derecha, que copia el bit de signo en lugar de rellenar con ceros.
An arithmetic right shift of 10011110 by 3 places gives the 8-bit pattern ____. · Un desplazamiento aritmético a la derecha de 10011110 en 3 posiciones produce el patrón de 8 bits ____.
The three vacated places on the left are filled with copies of the sign bit, 1, and the three rightmost bits 110 fall off. · Los tres lugares vacíos a la izquierda se rellenan con copias del bit de signo, 1, y los tres bits más a la derecha, 110, se pierden.
Cyclic shifts
- A cyclic shift 循环移位, or rotate, feeds the bit that drops off one end back in at the other end, so no bits are lost.
- A cyclic left shift of 1 on
10000110gives00001101: the leading 1 reappears on the right. - Logical shifts fill with zeros, arithmetic shifts fill with the sign bit, cyclic shifts fill with the bit that left. That is the whole difference between the three.
Desplazamientos cíclicos
- Un desplazamiento cíclico, o rotación, reintroduce el bit que cae de un extremo al otro extremo, por lo que no se pierden bits.
- Un desplazamiento cíclico a la izquierda de 1 sobre
10000110da00001101: el 1 inicial reaparece a la derecha. - Los desplazamientos lógicos se rellenan con ceros, los aritméticos con el bit de signo, los cíclicos con el bit que salió. Esa es toda la diferencia entre los tres.
A cyclic left shift of 1 place is applied to 10000110. What is the result? · Se aplica un desplazamiento cíclico a la izquierda de 1 posición a 10000110. ¿Cuál es el resultado?
The leading 1 leaves on the left and re-enters on the right, so no bit is lost. 00001100 would be the logical shift. · El 1 líder sale por la izquierda y vuelve a entrar por la derecha, por lo que no se pierde ningún bit. 00001100 sería el resultado de un desplazamiento lógico.
Worked example: 240 or minus 16?
- Take
11110000. Read as unsigned it is 240; read as two's complement it is −16. LSR #1brings in a 0 and gives01111000= 120, the correct half of 240.ASR #1copies the sign bit and gives11111000= −8, the correct half of −16.- Neither is wrong. Each halves the value under one reading, which is why a processor needs both instructions.
Ejemplo resuelto: ¿240 o menos 16?
- Tome
11110000. Leído como sin signo es 240; leído como complemento a dos es −16. LSR #1introduce un 0 y da01111000= 120, la mitad correcta de 240.ASR #1copia el bit de signo y da11111000= −8, la mitad correcta de −16.- Ninguno está mal. Cada uno reduce a la mitad el valor bajo una lectura, por eso un procesador necesita ambas instrucciones.
Which statements about the byte 11110000 are correct? Select all · todos that apply. · ¿Cuáles de las siguientes afirmaciones sobre el byte 11110000 son correctas? Seleccione todas las que correspondan.
The two results differ only in the bit that enters on the left: 0 for the logical shift, the sign bit for the arithmetic shift. · Los dos resultados difieren únicamente en el bit que entra por la izquierda: 0 para el desplazamiento lógico, el bit de signo para el desplazamiento aritmético.
Bit masking
- Embedded devices often use one bit 位 of a register per signal. A mask is a pattern combined with the register so that only the chosen bit changes.
- Set bit $n$:
ORwith a mask that has a 1 in position $n$. Clear bit $n$:ANDwith a mask that has a 0 there and 1s everywhere else. - Toggle bit $n$:
XORwith a mask that has a 1 there. Test bit $n$:ANDwith that mask, thenCMP #0: not equal means the bit was set.
Set with OR, clear with AND, toggle with XOR, each using a mask
Máscaras de bits
- Los dispositivos embebidos suelen usar un bit de un registro por señal. Una máscara es un patrón combinado con el registro para que solo cambie el bit elegido.
- Activar bit $n$:
ORcon una máscara que tenga un 1 en la posición $n$. Desactivar bit $n$:ANDcon una máscara que tenga un 0 ahí y 1s en todas partes. - Invertir bit $n$:
XORcon una máscara que tenga un 1 ahí. Probar bit $n$:ANDcon esa máscara, luegoCMP #0: diferente de cero significa que el bit estaba activado.

Activar con OR, desactivar con AND, invertir con XOR, cada uno usando una máscara
Match each bit operation to the bitwise operator (and mask) that does it. · Asocia cada operación de bits con el operador a nivel de bits (y la máscara) que la realiza.
OR sets, AND clears, XOR toggles, and AND + a non-zero test reads a bit — the four masking moves. · OR establece, AND borra, XOR alterna, y AND + una prueba no nula lee un bit: los cuatro movimientos de máscara.
To SET a particular bit to 1, you combine the register with a mask using: · Para ESTABLECER un bit particular en 1, se combina el registro con una máscara utilizando:
OR with a mask that has that bit = 1 forces the bit to 1 and leaves the others unchanged. · OR con una máscara que tiene ese bit = 1 fuerza el bit a 1 y deja los demás sin cambios.
Worked example: the instructions on one byte
- The ACC holds
10101100. The mask may be written#ndenary,Bnbinary or&nhexadecimal. AND B00001111gives00001100: only the low four bits survive.OR #1gives10101101: the least significant bit is set and nothing else moves.XOR &FFgives01010011: every bit inverted.AND B00001000thenCMP #0tests bit 3; the result00001000is not zero, so bit 3 was set.LSL #2gives10110000, losing the top two bits;LSR #3gives00010101.
Ejemplo resuelto: las instrucciones en un byte
- El ACC contiene
10101100. La máscara puede escribirse en decimal como#n, binario comoBno hexadecimal como&n. AND B00001111da00001100: solo sobreviven los cuatro bits inferiores.OR #1da10101101: el bit menos significativo está activado y nada más se mueve.XOR &FFda01010011: todos los bits invertidos.AND B00001000luegoCMP #0prueba el bit 3; el resultado00001000no es cero, así que el bit 3 estaba activado.LSL #2da10110000, perdiendo los dos bits superiores;LSR #3da00010101.
The instruction that sets the least significant bit of the ACC to 1 and leaves the other bits unchanged is OR ____. · La instrucción que establece el bit menos significativo del ACC en 1 y deja los otros bits sin cambios es OR ____.
OR with a mask that has a 1 only in the last place. Denary #1, binary B00000001 and hexadecimal &1 are the same mask. · OR con una máscara que tenga un 1 solo en la última posición. Denario #1, binario B00000001 y hexadecimal &1 son la misma máscara.
Put the steps for testing whether bit 3 of the ACC is set in order. · Ordena los pasos para probar si el bit 3 del ACC está activado.
Mask, compare, jump. The AND leaves either 00001000 or 00000000, and the compare with zero tells them apart. · Máscara, comparar, saltar. El AND deja ya sea 00001000 o 00000000, y la comparación con cero las distingue.
Monitoring and control, one bit at a time
- In a monitoring device one bit of a register per sensor means a single
ANDchecks whether a particular sensor is on. - In a control device one
ORswitches an actuator's control bit on without disturbing the others, and oneANDswitches it off. - It is fast, it uses almost no memory, and one byte holds eight independent on/off states. That is the "why" the exam asks for.
Monitoreo y control, un bit a la vez
- En un dispositivo de monitoreo, un bit de un registro por sensor significa que un único
ANDverifica si un sensor específico está activo. - En un dispositivo de control, un
ORactiva el bit de control de un actuador sin perturbar los demás, y unANDlo desactiva. - Es rápido, usa casi memoria y un byte mantiene ocho estados encendido/apagado independientes. Ese es el "por qué" que pregunta el examen.
Marks that slip away
- A left shift is × 2 per place only while the bits that fall off are zeros. Say so when a 1 is lost.
- A logical right shift brings in 0; an arithmetic right shift copies the sign bit. Choose by whether the number is signed.
- To clear a bit the mask needs a 0 at that bit and 1s everywhere else. A mask of all zeros clears the whole register.
XORtoggles; it does not set. To set useOR, to test useANDand compare with zero.
Puntos que se escapan
- Un desplazamiento a la izquierda es × 2 por lugar solo mientras los bits que caen sean ceros. Dígalo cuando se pierda un 1.
- Un desplazamiento lógico a la derecha introduce 0; un desplazamiento aritmético a la derecha copia el bit de signo. Elija según si el número tiene signo.
- Para desactivar un bit, la máscara necesita un 0 en ese bit y 1s en todas partes. Una máscara de todos ceros desactiva todo el registro.
XORinvierte; no activa. Para activar useOR, para probar useANDy compare con cero.
You've got it
- logical shift fills with 0: left × 2 per place, right ÷ 2, and lost 1s break the arithmetic
- arithmetic right shift copies the sign bit; a cyclic shift wraps the bit round
- masks: OR sets · AND clears · XOR toggles · AND then CMP #0 tests
- one bit per sensor or actuator makes monitoring and control fast and tiny; masks are written
#n,Bnor&n
Lo has entendido
- desplazamiento lógico se rellena con 0: izquierda × 2 por lugar, derecha ÷ 2, y los 1 perdidos rompen la aritmética
- desplazamiento aritmético a la derecha copia el bit de signo; un desplazamiento cíclico enrolla el bit alrededor
- máscaras: OR activa · AND desactiva · XOR invierte · AND luego CMP #0 prueba
- un bit por sensor o actuador hace que el monitoreo y control sean rápidos y pequeños; las máscaras se escriben
#n,Bno&n