News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

other code for not exceeding max value

Started by dsouza123, December 10, 2005, 12:38:46 AM

Previous topic - Next topic

dsouza123

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

Jimg


EduardoS

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.

dsouza123

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.

EduardoS

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
...



dsouza123

The last ( cmp i, 31 _ adc i, 0 ) is the best, two instructions, no jumps, flexible max value.