Binary shifts and bit manipulation · Deslocamentos binários e manipulação de bits
| English | Português |
|---|---|
| bit/bɪt/ | bit |
| mask/mæsk/ | máscara |
| logical shift/ˈlɒdʒɪkl ʃɪft/ | deslocamento lógico |
| sign bit/saɪn bɪt/ | bit de sinal |
| arithmetic right shift/ˌærɪθˈmetɪk raɪt ʃɪft/ | deslocamento aritmético à direita |
| cyclic shift/ˈsaɪklɪk ʃɪft/ | deslocamento 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.
Multiplicação em um chip que não pode multiplicar
- O processador do Game Boy de 1989 não tinha nenhuma instrução de multiplicação. Cada pontuação, cada coordenada que precisava ser dobrada era duplicada deslizando seus bits um lugar para a esquerda.
- Um deslocamento leva um ciclo de clock. A multiplicação construída a partir de deslocamentos e adições é como aqueles jogos rodavam em alguns kilobytes e algumas miliwatts.
- Os mesmos truques controlam fios individuais em um dispositivo embutido: um bit de um registro por sensor ou atuador, testado e definido com uma máscara 掩码.
- Esta lição são os três tipos de deslocamento e as quatro operações de máscara, nas instruções do próprio exame.
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)
Deslocamentos lógicos
- Um deslocamento lógico 逻辑移位 move cada bit para a esquerda ou direita por alguns lugares e preenche as posições vazias com 0.
LSL #1move os bits para a esquerda e um 0 entra pela direita: para um número sem sinal isso é × 2.LSR #1move-os para a direita e um 0 entra pela esquerda: integer ÷ 2.- Deslocar $n$ lugares multiplica ou divide por $2^{n}$.
00001011(11) apósLSL #1é00010110(22); apósLSR #1é00000101(5, o resto perdido).

Esquerda lógica (× 2), direita lógica (÷ 2) e direita aritmética (mantém o bit de sinal)
Shift and mask the bits of a byte · Desloque e mascare os bits de um 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. · Escolha um operador e veja cada bit resultante. Um deslocamento à esquerda (<<) moves every bit up one place (×2); a right shift (>>) move-os para baixo (÷2); AND com uma máscara limpa os bits que você não quer.
The 8-bit value 00001011 (11) is shifted left by 1 (LSL #1). What is the new denary value? · O valor de 8 bits 00001011 (11) é deslocado à esquerda em 1 (LSL #1). Qual é o novo valor decimal?
A left shift by 1 multiplies by 2: $11 \times 2 = 22$ (00010110). · Um deslocamento à esquerda em 1 multiplica por 2: $11 \times 2 = 22$ (00010110).
Shifting an unsigned number left by 3 places multiplies it by what number? · Deslocar um número sem sinal à esquerda em 3 posições multiplica-o por que número?
Shifting by $n$ places multiplies by $2^n$, so by 3 places is $2^3 = 8$. · Deslocar por $n$ posições multiplica por $2^n$, então por 3 posições é $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.
Exemplo resolvido: quando × 4 deixa de ser verdadeiro
- Bits deslocados fora da extremidade são perdidos, então a multiplicação só está correta enquanto eles eram zeros.
LSL #2no byte complemento de dois11001010resulta em00101000. Os dois 1s que caíram à esquerda se foram, o bit de sinal mudou e o resultado já não é mais quatro vezes o original.LSL #2em00001011(11) resulta em00101100(44), que está correto, porque apenas zeros foram perdidos.- O exame pede ambos: o padrão deslocado e um comentário sobre se o valor ainda está correto.
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
Deslocamento à direita aritmético
- Um simples deslocamento lógico à direita coloca um 0 no bit superior, o que tornaria um número complemento de dois negativo positivo.
- Um deslocamento à direita aritmético 算术右移 copia o bit de sinal 符号位 em cada posição vazia, então um número negativo permanece negativo e o deslocamento ainda divide por 2.
10011110deslocado aritmeticamente à direita em 3 posições resulta em11110011;01011100resulta em00001011.

Deslocamento lógico e aritmético à direita no mesmo byte: difere apenas no bit de entrada
An arithmetic right shift differs from a logical right shift because it: · Um deslocamento à direita aritmético difere de um deslocamento à direita lógico porque ele:
It preserves the sign bit, so dividing a negative signed number by a power of 2 keeps it negative. · Ele preserva o bit de sinal, então dividir um número sinalizado negativo por uma potência de 2 o mantém negativo.
A logical right shift always puts a 0 in the top bit, so it can turn a negative signed number positive. · Um deslocamento à direita lógico sempre coloca um 0 no bit superior, então pode tornar um número sinalizado negativo positivo.
That is exactly why signed division needs an arithmetic right shift, which copies the sign bit instead. · É exatamente por isso que a divisão sinalizada precisa de um deslocamento à direita aritmético, que copia o bit de sinal em vez disso.
An arithmetic right shift of 10011110 by 3 places gives the 8-bit pattern ____. · Um deslocamento à direita aritmético de 10011110 em 3 posições resulta no padrão 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. · Os três lugares vazios à esquerda são preenchidos com cópias do bit de sinal, 1, e os três bits mais à direita 110 caem fora.
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.
Deslocamentos cíclicos
- Um deslocamento cíclico 循环移位, ou rotate, alimenta o bit que cai em uma extremidade de volta na outra, assim nenhum bit é perdido.
- Um deslocamento cíclico à esquerda de 1 em
10000110resulta em00001101: o 1 inicial reaparece à direita. - Deslocamentos lógicos preenchem com zeros, deslocamentos aritméticos preenchem com o bit de sinal, deslocamentos cíclicos preenchem com o bit que saiu. Essa é toda a diferença entre os três.
A cyclic left shift of 1 place is applied to 10000110. What is the result? · Uma rotação à esquerda cíclica de 1 posição é aplicada a 10000110. Qual é o 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. · O 1 inicial sai pela esquerda e entra pela direita, então nenhum bit é perdido. 00001100 seria o deslocamento 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.
Exemplo resolvido: 240 ou menos 16?
- Pegue
11110000. Lido como sem sinal é 240; lido como complemento de dois é −16. LSR #1traz um 0 e resulta em01111000= 120, a metade correta de 240.ASR #1copia o bit de sinal e fornece11111000= −8, a metade correta de −16.- Nenhum está errado. Cada um divide o valor ao meio sob uma leitura, que é por que um processador precisa de ambas as instruções.
Which statements about the byte 11110000 are correct? Select all · todos that apply. · Quais afirmações sobre o byte 11110000 estão corretas? Selecione todos os que se aplicam.
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. · Os dois resultados diferem apenas no bit que entra pela esquerda: 0 para o deslocamento lógico, o bit de sinal para o deslocamento 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áscara de bits
- Dispositivos embutidos muitas vezes usam um bit 位 de um registro por sinal. Uma máscara é um padrão combinado com o registro para que apenas o bit escolhido mude.
- Definir bit $n$:
ORcom uma máscara que tem um 1 na posição $n$. Limpar bit $n$:ANDcom uma máscara que tem um 0 ali e 1s em todos os outros lugares. - Alternar bit $n$:
XORcom uma máscara que tem um 1 ali. Testar bit $n$:ANDcom aquela máscara, depoisCMP #0: diferente de zero significa que o bit estava definido.

Definir com OR, limpar com AND, alternar com XOR, cada um usando uma máscara
Match each bit operation to the bitwise operator (and mask) that does it. · Combine cada operação de bit com o operador bit-a-bit (e máscara) que a realiza.
OR sets, AND clears, XOR toggles, and AND + a non-zero test reads a bit — the four masking moves. · OR define, AND limpa, XOR alterna, e AND + um teste não-zero lê um bit — os quatro movimentos de máscara.
To SET a particular bit to 1, you combine the register with a mask using: · Para DEFINIR um bit específico como 1, você combina o registrador com uma máscara usando:
OR with a mask that has that bit = 1 forces the bit to 1 and leaves the others unchanged. · OR com uma máscara que tem esse bit = 1 força o bit a 1 e deixa os outros inalterados.
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.
Exemplo resolvido: as instruções em um único byte
- O ACC contém
10101100. A máscara pode ser escrita#ndecimal,Bnbinário ou&nhexadecimal. AND B00001111resulta em00001100: apenas os quatro bits baixos sobrevivem.OR #1resulta em10101101: o bit menos significativo é definido e nada mais muda.XOR &FFresulta em01010011: todos os bits invertidos.AND B00001000entãoCMP #0testa o bit 3; o resultado00001000não é zero, então o bit 3 estava definido.LSL #2resulta em10110000, perdendo os dois bits superiores;LSR #3resulta em00010101.
The instruction that sets the least significant bit of the ACC to 1 and leaves the other bits unchanged is OR ____. · A instrução que define o bit menos significativo do ACC como 1 e deixa os outros bits inalterados é 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 com uma máscara que tem um 1 apenas no último lugar. Decimal #1, binário B00000001 e hexadecimal &1 são a mesma máscara.
Put the steps for testing whether bit 3 of the ACC is set in order. · Coloque as etapas para testar se o bit 3 do ACC está definido em ordem.
Mask, compare, jump. The AND leaves either 00001000 or 00000000, and the compare with zero tells them apart. · Máscara, compare, salte. O AND deixa 00001000 ou 00000000, e a comparação com zero as 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.
Monitoramento e controle, um bit de cada vez
- Em um dispositivo de monitoramento, um bit de um registro por sensor significa que um único
ANDverifica se um sensor específico está ligado. - Em um dispositivo de controle, um
ORliga o bit de controle de um atuador sem perturbar os outros, e umANDo desliga. - É rápido, usa quase nenhuma memória e um byte mantém oito estados ligados/desligados independentes. Esse é o "porquê" que o exame pergunta.
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.
Marcas que escapam
- Um deslocamento à esquerda é × 2 por lugar apenas enquanto os bits que caem forem zeros. Diga isso quando um 1 for perdido.
- Um deslocamento lógico à direita traz 0; um deslocamento aritmético à direita copia o bit de sinal. Escolha dependendo se o número é com sinal.
- Para limpar um bit, a máscara precisa de um 0 naquele bit e 1s em todos os outros lugares. Uma máscara de todos zeros limpa todo o registro.
XORalterna; não define. Para definir useOR, para testar useANDe compare com zero.
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
Entendeu?
- deslocamento lógico preenche com 0: esquerda × 2 por lugar, direita ÷ 2, e 1s perdidos quebram a aritmética
- deslocamento à direita aritmético copia o bit de sinal; um deslocamento cíclico envolve o bit ao redor
- máscaras: OR define · AND limpa · XOR alterna · AND depois CMP #0 testa
- um bit por sensor ou atuador torna monitoramento e controle rápidos e pequenos; máscaras são escritas
#n,Bnou&n