Click to See Complete Forum and Search --> : Reversing a number


blinksumgreen
April 2nd, 2009, 10:39 PM
I am trying to reverse a number using either the shift or rotate commands, but am having some trouble.

In my mind, the following macro does this: reads in the variable, which I pass it elsewhere in the code (bottom chunk of code), then pulls the right most byte out of eAx and shoves it into the CF. I then pull the value out of the CF and shove it into the right most part of eBx.

Obviously some part of my logic/code is incorrect because it doesn't work.

Could anyone give me any tips on how to correct the algorithm?

_bitReverse Macro N:REQ

local L

mov eAx, &N ;moves the value located in N, into eAx

mov eCx, 0 ;sets the counter to 0
for1&L: cmp eCx, 32 ;tests to see if eCx < 32
jb do1&L
jmp endfor1&L
mov cl, 1
do1&L: SHR eAx, cl ;shift right on eAx (unsigned)
RCL eBx, cl ;shift left on eBx (unsigned)
inc eCx ;increments the counter (eCx)
jmp for1&L
endfor1&L:

mov eAx, eBx ;puts the reverse in eAx

endm

Lea edx, prompt
call writeString
call ReadDec

_bitReverse eAx

rxbagain
April 2nd, 2009, 11:53 PM
The problem is that you are shifting/rotating using the value of CL. EAX and EBX will change everytime you use SHR/RCL so you should shift/rotate bit 1 by 1. Your code should be like this

for1&L: cmp eCx, 32 ;tests to see if eCx < 32
jb do1&L
jmp endfor1&L
; mov cl, 1 - no need for this operation
do1&L: SHR eAx, 1 ;shift right on eAx (unsigned)
RCL eBx, 1 ;shift left on eBx (unsigned)
inc eCx ;increments the counter (eCx)
jmp for1&L
endfor1&L:

A better and shorter code is to initialize the counter (ECX to 32) and loop until 0

_bitReverse Macro N:REQ

local L

mov eax, &N ;moves the value located in N, into eAx
mov ecx, 32 ;sets the counter to 32
do1&L:
SHR eax, 1 ;shift right on eAx (unsigned)
RCL ebx, 1 ;rotate carry left on eBx (unsigned)
LOOP do1&L ;loop until ECX = 0
mov eAx, eBx ;puts the reverse in eAx

endm

Hope it will help you :)

blinksumgreen
April 7th, 2009, 10:38 PM
Thanks for the help!