Thursday, May 23, 2013

Using All 4 General Purpose Registers (And Immediate Values)

This time we are going to do a problem that makes us use all of the registers: eax,ebx,ecx, and edx.

1+4+8+2+3+6

mov eax, 1                 ;This changes eax into a 1
mov ebx, 4                 ;This changes ebx into a 4
add eax,ebx                ;This adds eax and ebx together which changes eax into a 5
mov ecx,eax               ;This copys eax down into ecx
mov eax,8                  ;This changes eax into an 8
mov ebx,2                  ;This changes ebx into a 2
add eax, ebx               ;This adds eax and ebx together which changes eax into an A
mov edx,eax               ;This copys eax into edx
mov eax,3                   ;This changes eax into a 3
mov ebx,6                   ;This changes ebx into a 6
add eax,ebx                 ;This adds eax and ebx together which changes eax into a 9
add eax,ecx                 ;This adds eax and ecx together which changes eax into a E
add eax,edx                 ;This adds eax and edx together which changes eax into a 18 in hex

This is a contrived example (meaning I just made it up). Here is a better way to solve 1+4+8+2+3+6


;1+4+8+2+3+6
mov eax,1
mov ebx,4
add eax,ebx
mov ebx,8
add eax,ebx
mov ebx,2
add eax,ebx
mov ebx,3
add eax,ebx
mov ebx,6
add eax,ebx

But we don't need to store numbers in registers before we use them.


;1+4+8+2+3+6
mov eax,1
add eax,4
add eax,8
add eax,2
add eax,3
add eax,6

You see? We didn't need to use any registers because those numbers are immediately available so it saves time because that way you don't have to go pull the number out of a register.  That's why these numbers are called immediate values.

No comments:

Post a Comment