For my first program I decided to toy around with mathematical operations.
I wanted to make a simple program that asks for an input X and Y and then performs Y^x and then displays the result.
For Example entering 2^38 will produce 274,877,906,944 which I know cannot fit on a 32 bit register (because 4,294,967,295 < 274,877,906,944).
The code example(s) I am about to post originate from Stackoverflow at (
https://stackoverflow.com/a/12681913).
Example 1:
xor edx,edx
mov eax,2 ; now you have 2 in edx:eax
mov ecx,38 ; 2^n, in this case 2^38 (any value x, 1 <= x <= 63, is valid).
x1: dec ecx ; decrease ecx by 1
jz ready ; if it's 2^1, we are ready.
shl eax,1 ; shift eax left through carry flag (CF) (overflow makes edx:eax zero)
rcl edx,1 ; rotate edx through carry flag (CF) left
jmp x1
ready: ; edx:eax contains now 2^38.
Example: 2
mov ecx,38 ; input (exponent) in ecx. 2^n, in this case 2^38.
; (any value x, 0 <= x <= 63, is valid).
; the code begins here.
xor eax,eax
xor edx,edx ; edx:eax is now prepared.
cmp cl,64 ; if (cl >= 64),
setb al ; then set eax to 0, else set eax to 1.
jae ready ; this is to handle cl >= 64.
; now we have 0 <= cl <= 63
sub ecx,1
setnc al ; if (count == 0) then eax = 0, else eax = 1.
lea eax,[eax+1] ; eax = eax + 1. does not modify any flags.
jna ready ; 2^0 is 1, 2^1 = 2, those are ready now.
mov ebx,ecx ; copy ecx to ebx
cmp cl,32 ; if (cl >= 32)
jb low_5_bits
mov cl,31 ; then shift first 31 bits to the left.
shld edx,eax,cl
shl eax,cl ; now shifted 31 bits to the left.
lea ecx,[ebx-31] ; cl = bl - 31
low_5_bits:
shld edx,eax,cl
shl eax,cl
ready:
What I gather is that bit shifting is taking place to make values small enough to fit into registers. Correct?
The following below is what I can make out from reading the codes.
Example 1: Utilizes Jumps based on Conditionals
(1) First xor is used to set the registers to 0
(2) 2 is then moved into the eax register
(3) 38 is then moved into the ecx register
(4) The value in ecx is decreased by 1 and the it loops until a certain value is reached, How would verify that the answer is and print it to a win32 window. (This is where I am confused at. When i run the code I get values in the registers that are not 274,877,906,944) so i assume that i need to perform another step to get the expected value.
Example 2: Doesn't utilize jumps, I gather that its making use of byte shifting to alter values which is a concept I understand through reading about it. (I picked x86 assembly as the first programming language to learn ,painful; but I do not regret it.)
(1) I cant explain code much farther, except the fact that it is using a different method or algorithm?
Can someone give a an explanation as to how the code would arrive at 274,877,906,944 through bit shifting, it would help me progress.
This may be off-topic, but do stacks operate in a similar fashion that RPN calculators operate (Ignore if you want).
Forgive any grammar/typos