The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: dsouza123 on December 10, 2005, 12:38:46 AM

Title: other code for not exceeding max value
Post by: dsouza123 on December 10, 2005, 12:38:46 AM
What code can keep a dword from exceeding some max value
without doing

max dd 31
i dd 0

.if i > max
  mov i, max
.endif


with the .if

  mov i, 0
  .repeat
    inc i
    .if i > 31
      mov i, 31
    .endif
    more...code
  .until done == 1

tried without

  mov i, 0
  .repeat
    inc i
    and i, 31
    more...code
  .until done == 1


but after i gets to 31 it goes back to 0
instead of remaining at 31

hoped to get 1,2,...31,31,31,31
Title: Re: other code for not exceeding max value
Post by: Jimg on December 10, 2005, 01:43:37 AM
try-

.if i<31
  inc i
.endif
Title: Re: other code for not exceeding max value
Post by: EduardoS on December 10, 2005, 02:27:25 AM
you won't get the expected result with and,
and i, 31
is the same as i = i mod 32

in this case to avoid if you can do

cmp i, 31
sbb i, 0

or

cmp i, 31
cmovc i, 31

or millions others possibilities.
Title: Re: other code for not exceeding max value
Post by: dsouza123 on December 11, 2005, 12:32:06 AM
Thanks for the replies.

Tested

.if i<31
  inc i
.endif

it works

also

cmp i, 31
sbb i, 0

it needed a slight tweek and an instruction


cmp i, 32
cmc
sbb i, 0


other code that works


.data
n31 dd not 31

.code
mov eax, n31
add eax, i
sbb dcnt, 0


After more thinking about the issue, it really is a saturated add with 5 bits.
Title: Re: other code for not exceeding max value
Post by: EduardoS on December 11, 2005, 04:08:13 AM
Quote from: dsouza123 on December 11, 2005, 12:32:06 AM
also

cmp i, 31
sbb i, 0

it needed a slight tweek and an instruction


cmp i, 32
cmc
sbb i, 0


true, my mistake, to avoid the cmc you should put 31 in one register and make cmp reg, i instead of cmp i, 31, the code becomes:

mov edx, 31
startloop:
inc i
cmp edx, i
sbb i, 0
...

but a better option is:

start loop:
cmp i, 31
adc i, 0
...


Title: Re: other code for not exceeding max value
Post by: dsouza123 on December 11, 2005, 04:51:49 AM
The last ( cmp i, 31 _ adc i, 0 ) is the best, two instructions, no jumps, flexible max value.