79
Web site Examples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this slide show for your personal use, or for use in the classroom, as long as this copyright statement, the author's name, and the title are not changed. Slides prepared by the author Revision date: June 4, 2006 Kip R. Irvine

Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Embed Size (px)

Citation preview

Page 1: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Capítulo 7: Aritmética de Inteiros

(c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this slide show for your personal use, or for use in the classroom, as long as this copyright statement, the author's name, and the title are not changed.

Slides prepared by the author

Revision date: June 4, 2006

Kip R. Irvine

Page 2: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

ÍndiceInstruções de Shift e Rotate Aplicações de Shift e Rotate Instruções de Multiplicação e DivisãoAdição e subtração estendidaAritmética ASCII e decimal desempacotadoAritmética decimal empacotado

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

2

Page 3: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instruções de Shift e Rotate Shift Lógico vs Aritmético Instrução SHL Instrução SHR Instruções SAL e SAR Instrução ROL Instrução ROR Instruções RCL e RCR Instruções SHLD/SHRD

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

3

Page 4: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Shift lógico vs. aritméticoO shift lógico preenche as lacunas criadas com zero:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

4

• O shift aritmético preenche as lacunas criadas com a cópia do bit de sinal:

Page 5: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução SHL A instrução SHL (shift left) faz o deslocamento lógico

à esquerda do operando destino, preenchendo o bit à direita com 0.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

5

• Tipos de operando para SHL:

SHL reg,imm8SHL mem,imm8SHL reg,CLSHL mem,CL

(mesmos para todas as instruções shift e rotate)

Page 6: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 6

mov dl,5shl dl,1

Deslocando 1 bit à esquerda multiplica um número por 2

mov dl,5shl dl,2 ; DL = 20

Deslocando à esquerda n bits multiplica o operando por 2n

Exemplo, 5 * 22 = 20

Page 7: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução SHR A instrução SHR (shift right) faz o deslocamento lógico à

direita do operando destino. A posição do bit mais significativo é preenchido com zero.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

7

mov dl,80shr dl,1 ; DL = 40shr dl,2 ; DL = 10

Deslocando n bits à direita divide o operando por 2n

Page 8: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instruções SAL e SAR SAL (shift arithmetic left) é idêntico a SHL.SAR (shift arithmetic right) faz um deslocamento

aritmético à direita no operando destino.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 8

Um shift aritmético preserva o sinal do número.

mov dl,-80sar dl,1 ; DL = -40sar dl,2 ; DL = -10

Page 9: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

9

mov al,6Bhshr al,1 a.shl al,3 b.mov al,8Chsar al,1 c.sar al,3 d.

Indicar o valor em hexadecimal de AL após cada shift:

35hA8h

C6hF8h

Page 10: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução ROLROL (rotate) desloca cada bit à esquerdaO bit mais significativo é copiado no flag Carry e

no bit menos significativoNenhum bit é perdido

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

10

mov al,11110000brol al,1 ; AL = 11100001b

mov dl,3Fhrol dl,4 ; DL = F3h

Page 11: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução ROR ROR (rotate right) desloca cada bit à direitaO bit menos significativo é copiado no flag Carry e na

posição do bit mais significativoNenhum bit é perdido

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

11

mov al,11110000bror al,1 ; AL = 01111000b

mov dl,3Fhror dl,4 ; DL = F3h

Page 12: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

12

mov al,6Bhror al,1 a.rol al,3 b.

Indicar o valor hexadecimal de AL após cada rotação:

B5hADh

Page 13: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução RCLRCL (rotate carry left) desloca cada it à esquerdaCopia o Carry flag para a posição menos significativaCopia o bit mais significativo no flag Carry

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

13

CF

clc ; CF = 0mov bl,88h ; CF,BL = 0 10001000brcl bl,1 ; CF,BL = 1 00010000brcl bl,1 ; CF,BL = 0 00100001b

Page 14: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução RCRRCR (rotate carry right) desloca cada bit à direitaCopia o flag Carry na posição mais significativaCopia o bit menos significativo no flag Carry

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

14

stc ; CF = 1mov ah,10h ; CF,AH = 1 00010000brcr ah,1 ; CF,AH = 0 10001000b

Page 15: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

15

stcmov al,6Bhrcr al,1 a.rcl al,3 b.

Indicar o valor hexadecimal de AL após cada rotação:

B5hAEh

Page 16: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução SHLDDesloca o operando destino um dado número de bits à esquerda As posições vazias resultantes são preenchidas pelos bits mais

significativos do operando fonteO operando fonte não é afetadoSintaxe:

SHLD destination, source, countTipos de operando:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

16

SHLD reg16/32, reg16/32, imm8/CL

SHLD mem16/32, reg16/32, imm8/CL

Page 17: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplo de SHLD

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

17

.datawval WORD 9BA6h.codemov ax,0AC36hshld wval,ax,4

Desloca wval 4 bits à esquerda e substitui os 4 bits menos significativos com os 4 bits mais significativos de AX:

Before:

After:

Page 18: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução SHRDDesloca o operando destino um dado número de bits à

direitaAs posições vazias resultantes são preenchidas com os

bits menos significativos do operando fonteO operando fonte não é afetadoSintaxe:

SHRD destination, source, countTipos de operando:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

18

SHRD reg16/32, reg16/32, imm8/CL

SHRD mem16/32, reg16/32, imm8/CL

Page 19: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplo de SHRD

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

19

mov ax,234Bhmov dx,7654hshrd ax,dx,4

Desloca AX 4 bits à direita e substitui os 4 bits mais significativos com os 4 bits menos significativos de DX:

Before:

After:

Page 20: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Sua vez . . .

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

20

mov ax,7C36hmov dx,9FA6hshld dx,ax,4 ; DX =shrd dx,ax,8 ; DX =

Indicar em valor hexadecimal cada operando destino:

FA67h36FAh

Page 21: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Próxima seçãoInstruções de Shift e Rotate Aplicações de Shift e Rotate Instruções de Multiplicação e DivisãoAdição e subtração estendidaAritmética ASCII e decimal desempacotadoAritmética decimal empacotado

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

21

Page 22: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Aplicações de Shift e Rotate

Deslocando Doublewords múltiplosMultiplicação binária Mostrando bits binários Isolando uma cadeia de bits

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

22

Page 23: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Deslocando Doublewords múltiplosOs programas às vezes precisam deslocar todos os bits

de um vetor, como o movimento de uma imagem gráfica de uma posição da tela para outra.

O seguinte programa desloca um vetor de 3 doublewords 1 bit à direita:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

23

.dataArraySize = 3array DWORD ArraySize DUP(99999999h) ; 1001 1001....codemov esi,0shr array[esi + 8],1 ; high dwordrcr array[esi + 4],1 ; middle dword, include Carryrcr array[esi],1 ; low dword, include Carry

Page 24: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Multiplicação bináriaSabemos que SHL faz a multiplicação sem sinal quando

o multiplicador é potência de 2. É possível fatorar qualquer número binário em potência

de 2. Por exemplo, para multiplicar EAX * 36, fatorar 36 em

32 + 4 e usar a propriedade distributiva de multiplicação :

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

24

EAX * 36 = EAX * (32 + 4)= (EAX * 32)+(EAX * 4)

mov eax,123mov ebx,eaxshl eax,5 ; mult by 25

shl ebx,2 ; mult by 22

add eax,ebx

Page 25: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

25

mov ax,2 ; test value

mov dx,axshl dx,4 ; AX * 16push dx ; save for latermov dx,axshl dx,3 ; AX * 8shl ax,1 ; AX * 2add ax,dx ; AX * 10pop dx ; recall AX * 16add ax,dx ; AX * 26

Multiplicar AX por 26, usando deslocamento e adição.

Dica: 26 = 16 + 8 + 2.

Page 26: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Mostrando bits bináriosAlgoritmo: deslocar o MSB para o flag Carry; se CF = 1, anexar o caractere "1“ à cadeia; caso contrário, anexar o caractere “0” . Repetir em loop, 32 vezes.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

26

.databuffer BYTE 32 DUP(0),0.code

mov ecx,32mov esi,OFFSET buffer

L1: shl eax,1mov BYTE PTR [esi],'0'jnc L2mov BYTE PTR [esi],'1'

L2: inc esiloop L1

Page 27: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Isolando uma cadeia de bitsO campo de data do arquivo MS-DOS empacota o

ano, mês e dia em 16 bits:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

27

mov ax,dx ; make a copy of DXshr ax,5 ; shift right 5 bitsand al,00001111b ; clear bits 4-7mov month,al ; save in month variable

Isolar o campo mês:

Page 28: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

28

Próxima seçãoInstruções de Shift e Rotate Aplicações de Shift e Rotate Instruções de Multiplicação e DivisãoAdição e subtração estendidaAritmética ASCII e decimal desempacotadoAritmética decimal empacotado

28

Page 29: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instruções de Multiplicação e Divisão

Instrução MUL Instrução IMUL Instrução DIV Divisão inteira com sinalInstruções CBW, CWD, CDQ Instrução IDIV Implementando expressões Aritméticas

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

29

Page 30: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução MULA instrução MUL (unsigned multiply) multiplica um operando de 8-,

16-, ou 32-bit por AL, AX, ou EAX.

Os formatos são:MUL r/m8

MUL r/m16

MUL r/m32

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

30

Operandos implícitos:

Page 31: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de MUL

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

31

100h * 2000h, usando operandos de 16-bits:

.dataval1 WORD 2000hval2 WORD 100h.codemov ax,val1mul val2 ; DX:AX = 00200000h, CF=1

O flag Carry indica se a metade superior contem dígitos significativos

mov eax,12345hmov ebx,1000hmul ebx ; EDX:EAX = 0000000012345000h, CF=0

12345h * 1000h, usando operandos de 32-bits:

Page 32: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

32

mov ax,1234hmov bx,100hmul bx

Quais seriam os valores em hexadecimal de DX, AX, e flag Carry após a execução das instruções seguintes?

DX = 0012h, AX = 3400h, CF = 1

Page 33: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

33

mov eax,00128765hmov ecx,10000hmul ecx

Quais serão os valores em hexadecimal de EDX, EAX, e flag Carry após a execução das seguintes instruções?

EDX = 00000012h, EAX = 87650000h, CF = 1

Page 34: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução IMULIMUL (signed integer multiply ) multiplica um operando

com sinal de 8-, 16-, ou 32-bits por AL, AX, ou EAXPreserva o sinal do produto estendendo o sinal para o

registrador destino da metade mais significativa

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

34

Exemplo: multiplicar 48 * 4, usando operandos de 8-bits :

mov al,48mov bl,4imul bl ; AX = 00C0h, OF=1

OF=1 porque AH recebe bits significativos, não somente extensão de sinal de AL.

Page 35: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de IMUL

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

35

Multiplicar 4,823,424 * 423:

mov eax,4823424mov ebx,-423imul ebx ; EDX:EAX = FFFFFFFF86635D80h, OF=0

OF=0 porque EDX é somente extensão de sinal de EAX.

Page 36: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

36

mov ax,8760hmov bx,100himul bx

Quais serão os valores hexadecimal de DX, AX, flag Carry e overflow flag após a execução das seguintes instruções?

DX = FF87h, AX = 6000h, CF=1, OF = 1

Page 37: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução DIV (sem sinal) A instrução DIV faz a divisão de 8-bit, 16-bit, e 32-bits

em inteiros sem sinalO divisor é o único operando explícito (registrador ou

memória)Formatos:

DIV r/m8

DIV r/m16

DIV r/m32

37

Operandos Default:

Page 38: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de DIV

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 38

Dividir 8003h por 100h, usando operandos de 16-bits:

mov dx,0 ; clear dividend, highmov ax,8003h ; dividend, lowmov cx,100h ; divisordiv cx ; AX = 0080h, DX = 3

Mesma divisão, usando operandos de 32-bits:

mov edx,0 ; clear dividend, highmov eax,8003h ; dividend, lowmov ecx,100h ; divisordiv ecx ; EAX = 00000080h, EDX = 3

Page 39: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

39

mov dx,0087hmov ax,6000hmov bx,100hdiv bx

Quais os valores em hexadecimal de DX e AX após a execução das seguintes instruções? Ou, indicar se ocorre divide overflow:

DX = 0000h, AX = 8760h

Page 40: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

40

mov dx,0087hmov ax,6002hmov bx,10hdiv bx

Quais os valores em hexadecimal de DX e AX após a execução das seguintes instruções? Ou, indicar se ocorrer divide overflow:

Divide Overflow

Page 41: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

IDIV - Divisão inteira com sinal Os inteiros com sinal devem ser estendidos em sinal antes

da divisão ser realizadaPreencher os byte/word/doubleword mais significativos

com uma cópia do bit de sinal do byte/word/doubleword menos significativo

Por exemplo, o byte mais significativo contem uma cópia do bit de sinal do byte menos significativo:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

41

Page 42: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instruções CBW, CWD, CDQ As instruções CBW, CWD e CDQ realizam

importantes operações de extensão de sinal:CBW (convert byte to word) estende AL para AHCWD (convert word to doubleword) estende AX para DXCDQ (convert doubleword to quadword) estende EAX para EDX

Exemplo: mov eax,0FFFFFF9Bh ; (-101)cdq ; EDX:EAX = FFFFFFFFFFFFFF9Bh

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

42

Page 43: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução IDIVIDIV faz a divisão de inteiro com sinalMesma sintaxe e operandos como na instrução DIV

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

43

Exemplo: divisão de 8-bits de –48 por 5

mov al,-48cbw ; extend AL into AHmov bl,5idiv bl ; AL = -9, AH = -3

Page 44: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de IDIV

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 44

Exemplo: divisão de 32-bits de –48 por 5

mov eax,-48cdq ; extend EAX into EDXmov ebx,5idiv ebx ; EAX = -9, EDX = -3

Exemplo: divisão de 16-bits de –48 por 5

mov ax,-48cwd ; extend AX into DXmov bx,5idiv bx ; AX = -9, DX = -3

Page 45: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

45

mov ax,0FDFFh ; -513cwdmov bx,100hidiv bx

Quais os valores em hexadecimal de DX e AX após a execução das seguintes instruções? Ou, se ocorrer divide overflow , indicar isso como resposta:

DX = FFFFh (1), AX = FFFEh (2)

Page 46: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Expressões aritméticas sem sinalAlgumas boas razões para aprender expressões de inteiros:

Aprender como compiladores as fazemTestar o entendimento de MUL, IMUL, DIV, IDIVCheck de overflow (flags Carry e Overflow )

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 46

Exemplo: var4 = (var1 + var2) * var3

; Assume unsigned operandsmov eax,var1add eax,var2 ; EAX = var1 + var2mul var3 ; EAX = EAX * var3jc TooBig ; check for carrymov var4,eax ; save product

Page 47: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Expressões aritmética com sinal (1 de 2)

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 47

Exemplo: eax = (-var1 * var2) + var3

mov eax,var1neg eaximul var2jo TooBig ; check for overflowadd eax,var3jo TooBig ; check for overflow

Exemplo: var4 = (var1 * 5) / (var2 – 3)

mov eax,var1 ; left sidemov ebx,5imul ebx ; EDX:EAX = productmov ebx,var2 ; right sidesub ebx,3idiv ebx ; EAX = quotientmov var4,eax

Page 48: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Expressões aritmética com sinal (2 de 2)

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

48

Exemplo : var4 = (var1 * -5) / (-var2 % var3);

mov eax,var2 ; begin right sideneg eaxcdq ; sign-extend dividendidiv var3 ; EDX = remaindermov ebx,edx ; EBX = right sidemov eax,-5 ; begin left sideimul var1 ; EDX:EAX = left sideidiv ebx ; final divisionmov var4,eax ; quotient

As vezes é mais fácil calcular o termo à direita primeiro.

Page 49: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

49

mov eax,20imul ebxidiv ecx

Implementar a seguinte expressão usando inteiros de 32 bits com sinal:

eax = (ebx * 20) / ecx

Page 50: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

50

push edxpush eax ; EAX needed latermov eax,ecximul edx ; left side: EDX:EAXpop ebx ; saved value of EAXidiv ebx ; EAX = quotientpop edx ; restore EDX

Implementar a seguinte expressão usando inteiros de 32 bits com sinal. Salvar e restaurar EDX:

eax = (ecx * edx) / eax

Page 51: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

51

mov eax,var1mov edx,var2neg edximul edx ; left side: EDX:EAXmov ecx,var3sub ecx,ebxidiv ecx ; EAX = quotientmov var3,eax

Implementar a seguinte expressão usando inteiros de 32 bits com sinal. Não modificar nenhuma variável a não ser var3:

var3 = (var1 * -var2) / (var3 – ebx)

Page 52: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples52

Próxima seçãoInstruções de Shift e Rotate Aplicações de Shift e Rotate Instruções de Multiplicação e DivisãoAdição e subtração estendidaAritmética ASCII e decimal desempacotadoAritmética decimal empacotado

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

52

Page 53: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Adição e subtração estendidaInstrução ADC Extended Precision AdditionInstrução SBBExtended Precision Subtraction

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

53

Page 54: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Adição com precisão estendidaAdicionando 2 operandos que são maiores que o tamanho

máximo da palavra (32 bits).Virtualmente não deve existir limite para o tamanho dos

operandos

A aritmética deve ser realizada em etapasO valor de Carry de uma etapa é passado para a próxima

etapa.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

54

Page 55: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução ADCA instrução ADC soma o operando fonte e o flag de

Carry ao operando destino.Operandos são valores binários

Mesma sintaxe do ADD, SUB, etc.Exemplo Somar dois inteiros de 32-bits (FFFFFFFFh +

FFFFFFFFh), produzindo uma soma de 64-bit em EDX:EAX:

mov edx,0mov eax,0FFFFFFFFhadd eax,0FFFFFFFFhadc edx,0 ;EDX:EAX = 00000001FFFFFFFEh

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

55

Page 56: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplo de adição com precisão estendida

Tarefa: somar 1 a EDX:EAXValor inicial de EDX:EAX: 00000000FFFFFFFFhSomar os 32 bits menos significativos primeiro, acionando o flag Carry. Somar os 32 bits mais significativos, e incluir o flag Carry.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 56

mov edx,0 ; set upper halfmov eax,0FFFFFFFFh ; set lower halfadd eax,1 ; add lower halfadc edx,0 ; add upper half

EDX:EAX = 00000001 00000000

Page 57: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução SBB

A instrução SBB subtrai o operando fonte e o flag Carry do operando destino.

sintaxe:Mesmo que a instrução ADC

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

57

Page 58: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplo de subtração estendidaTarefa: Subtrair 1 de EDX:EAX

Valor inicial de EDX:EAX: 0000000100000000h Subtrair os 32 bits menos significativos primeiro, acionando o flag Carry. Subtrair os 32 bits mais significativos, incluindo o flag Carry.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 58

mov edx,1 ; set upper halfmov eax,0 ; set lower halfsub eax,1 ; subtract lower halfsbb edx,0 ; subtract upper half

EDX:EAX = 00000000 FFFFFFFF

Page 59: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples59

Próxima seçãoInstruções de Shift e Rotate Aplicações de Shift e Rotate Instruções de Multiplicação e DivisãoAdição e subtração estendidaAritmética ASCII e decimal desempacotadoAritmética decimal empacotado

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

59

Page 60: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Aritmética ASCII e decimal empacotado

Binary Coded DecimalASCIIInstrução AAA Instrução AAS Instrução AAM Instrução AAD Inteiros em decimal empacotado Instrução DAA Instrução DAS

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

60

Page 61: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Binary-Coded Decimal (BCD)Um BCD usa 4 bits para representar o dígito decimalUm número em BCD desempacotado tem um dígito

decimal na parte menos significativa dos bytes

Por exemplo, 5,678 é armazenado na seguinte seqüência de bytes mostrados em hexadecimal:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

61

05 06 07 08

Page 62: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

ASCII Nessa representação, é usado o código ASCII do

número

Por exemplo, 5,678 é armazenado na seguinte seqüência de bytes mostrados em hexadecimal:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

62

35 36 37 38

Page 63: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução AAA (adjust after addition) Ajusta o resultado binário de uma instrução ADD ou ADC, em

números ASCIITorna o resultado em AL consistente com o BCD.

O valor Carry, se existir termina em AH

Para converter o resultado em ASCII fazer or ax, 3030h

Exemplo: somar ‘8’ e ‘2’

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

mov ah,0mov al,'8' ; AX = 0038hadd al,'2' ; AX = 006Ahaaa ; AX = 0100h (adjust result)or ax,3030h ; AX = 3130h = '10'

Page 64: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução AAS (adjust after subtraction)Ajusta o resultado binário de uma instrução SUB ou SBB, em números ASCII . Torna o resultado em AL consistente com BCD.

Coloca o valor Carry , se houver, em AH

Para converter o resultado em ASCII fazer or ax, 3030h

Exemplo : Subtrair ‘8' de ‘9'

64

mov ah,0mov al,‘9' ; AX = 0039hsub al,‘8' ; AX = 0001haas ; AX = 0001h, CF=0or ax,3030h ; AX = ‘01'

Page 65: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução AAM (ASCII adjust after multiplication)

Ajusta o resultado binário de uma instrução MUL. A multiplicação deve usar BCD desempacotado.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

65

mov bl,05h ; first operandmov al,06h ; second operandmul bl ; AX = 001Ehaam ; AX = 0300h

Page 66: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução AAD (ASCII adjust before division)Converte o dividendo em BCD desempacotado, para

binário, antes da operação de divisão

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

66

.dataquotient BYTE ?remainder BYTE ?.codemov ax,0307h ; dividendaad ; AX = 0025hmov bl,5 ; divisordiv bl ; AX = 0207hmov quotient,almov remainder,ah

Page 67: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

67

Próxima seçãoInstruções de Shift e Rotate Aplicações de Shift e Rotate Instruções de Multiplicação e DivisãoAdição e subtração estendidaAritmética ASCII e decimal desempacotadoAritmética decimal empacotado

67

Page 68: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Decimal ou BCD empacotadoInteiros em decimal ou BCD empacotado armazena

dois dígitos decimais por byte Por exemplo, 12,345,678 pode ser armazenado como a

seguinte seqüência de bytes em hexadecimal:

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

68

12 34 56 78

Bom para valores financeiros –é possível estender a precisão, sem arredondamento de erros.

Page 69: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução DAA (decimal adjust after addition)Converte o resultado binário de uma operação ADD

ou ADC para o formato decimal empacotado.O valor a ser ajustado deve estar em ALSe o dígito menos significativo é alterado, o flag de

Auxiliary Carry é acionado.Se o dígito mais significativo é alterado, o flag de Carry

é acionado.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

69

Page 70: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Lógica DAA If (AL(lo) > 9) or (AuxCarry = 1)

AL = AL + 6

AuxCarry = 1

Else

AuxCarry = 0

Endif

If (AL(hi) > 9) or Carry = 1

AL = AL + 60h

Carry = 1

Else

Carry = 0

Endif

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 70

se AL = AL + 6 aciona o flag de Carry, esse valor de carry é usado na avaliação de AL(hi).

Page 71: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de DAA Exemplo : calcular BCD 35 + 48

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 71

mov al,35hadd al,48h ; AL = 7Dhdaa ; AL = 83h, AF= 1, CF = 0

• Exemplo : calcular BCD 35 + 65

mov al,35hadd al,65h ; AL = 9Ahdaa ; AL = 00h, AF = 1, CF = 1

• Exemplo : calcular BCD 69 + 29

mov al,69hadd al,29h ; AL = 92h, AF = 1daa ; AL = 98h, AF = 1, CF = 0

Page 72: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Sua vez . . .

Um mal funcionamento temporário no computador desabilitou a instrução DAA. Escrever um procedimento em linguagem Assembly que realiza as mesmas ações do DAA.

Testar o procedimento usando os valores do slide anterior.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

72

Page 73: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Instrução DASA instrução DAS (decimal adjust after subtraction)

converte o resultado binário de uma operação SUB ou SBB para o formato decimal empacotado.

O valor deve estar em ALExemplo : subtrair BCD 35 de 48

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

73

mov al,48hsub al,35h ; AL = 13hdas ; AL = 13h, CF = 0

Page 74: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Lógica de DAS

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

74

If (AL(lo) > 9) OR (AuxCarry = 1)AL = AL − 6;AuxCarry = 1;

ElseAuxCarry = 0;

Endif

If (AL > 9FH) or (Carry = 1)AL = AL − 60h;Carry = 1;

ElseCarry = 0;

Endif

se AL = AL 6 aciona o flag de Carry, esse valor é usado na avaliação de AL no segundo IF

Page 75: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de DAS (1 de 2)

Exemplo : subtrair BCD 48 – 35

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 75

mov al,48hsub al,35h ; AL = 13hdas ; AL = 13h, AF=0, CF = 0

• Exemplo : subtrair BCD 62 – 35

mov al,62hsub al,35h ; AL = 2Dh, AF = 1, CF = 0das ; AL = 27h, AF = 1, CF = 0

• Exemplo : subtrair BCD 32 – 29

mov al,32hsub al,29h ; AL = 09h, AF = 1, CF = 0das ; AL = 03h, AF = 1, CF = 0

Page 76: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Exemplos de DAS (2 de 2)

Example: subtrair BCD 32 – 39

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 76

mov al,32hsub al,39h ; AL = F9h, AF = 1, CF = 1das ; AL = 93h, AF = 1, CF = 1

Steps: AL = F9hAF = 1, so subtract 6 from F9hAL = F3hF3h > 9Fh, so subtract 60h from F3hAL = 93h, CF = 1

Page 77: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

Sua vez . . .

Um mal funcionamento temporário do computador desabilitou a instrução DAS . Escrever um procedimento em linguagem Assembly que realiza as mesmas ações do DAS.

Testar o procedimento usando os valores dos dois slides anteriores.

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

77

Page 78: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site Examples

SumárioInstruções Shift e rotate são algumas das melhores

ferramentas da linguagem assemblyControle mais fino que em linguagens de alto nívelSHL, SHR, SAR, ROL, ROR, RCL, RCR

MUL e DIV – operações inteirasPróximas de SHL e SHRCBW, CDQ, CWD: preparação para divisão

Aritmética de precisão estendida: ADC, SBBOperações decimal ASCII (AAA, AAS, AAM, AAD)Operações decimal empacotado (DAA, DAS)

Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

78

Page 79: Web siteWeb site ExamplesExamples Capítulo 7: Aritmética de Inteiros (c) Pearson Education, 2006-2007. All rights reserved. You may modify and copy this

Web site ExamplesIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007. 79