News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests

Main Menu

Why this code is doing the opposite of what I expect

Started by masterori, March 01, 2016, 05:19:02 PM

Previous topic - Next topic

masterori


mov edx,offset buffer               ; lets say this buffer contains '123'
call WriteString                        ; will print out '123'

mov esi,offset buffer

; first char is '1' which has ASCII of 49
mov ebx,47
cmp ebx,[esi]
jg error

mov ebx,58
cmp ebx,[esi]
jl error                                ; it keeps jumping to error. but 58 is not less than 49

Can someone explain why it keeps jumping to error when comparing 58 to 49? I'm trying to do this if 48 <= bufferVal <= 57 then ...

TouEnMasm


mov eax,[buffer]  ;dword ptr buffervalue

.if eax >= 48 && eax <= 57
     ;do somenthing
.else
      call error
.endif
Fa is a musical note to play with CL

rrr314159

In this statement:

cmp ebx, [esi]

you're comparing the next 4 bytes (dword) at address esi, which is a large number (49 + 50*256 + 51*256^2). Instead use

cmp bl, [esi]

which will compare only one byte (49).

Of course, there are many other ways to handle the problem ...
I am NaN ;)

i Z !

 
For comparing bytes or other non-negative values, consider using JB/JA instead of JG/JL .

dedndave

yah - ascii characters are unsigned - JA, JAE, JB, JBE should be used
if you use .if/.else/.endif, unsigned branches are used by default

in the first reply, ToutEnMasm is close, but the ascii characters are not dwords
but - one thing is good - load the byte to compare into a register
that reduces memory accesses when making 2 compares

.if/.else/.endif type constructs don't always lend themselves to workable code

i am guessing that the "..." in this statement is the non-error case ?   :P
if 48 <= bufferVal <= 57 then ...

mov esi,offset buffer

; first char is '1' which has ASCII of 49
mov al,[esi]
cmp al,48
jb error

cmp al,57
ja error

non_error_case:

dedndave

it makes sense to test the higher case first, because it is more likely that the char will be above

mov esi,offset buffer

; first char is '1' which has ASCII of 49
mov al,[esi]
cmp al,57
ja error

cmp al,48
jb error

non_error_case:

sinsi