A
A
Alrond21982020-08-17 20:42:42
assembler
Alrond2198, 2020-08-17 20:42:42

How to work with negative numbers in assembler?

Goal: Compute (2*a/b-1)/(a-28+c) in an assembler function called from a C++ file.
Problem: an assembler function from time to time perceives a certain number not as negative in the additional code or as it is there, but as positive.
This is how the parameters are declared in the C++ file:

extern "C"
{
    signed __int8 a = 0, b = 1, c = 29;
    signed __int8 numerator = 0;
    signed __int16 denominator = 0;
    signed __int8 result = 0;
    void ASM_count();
}


This is what the assembler file looks like:
;.586
;.model large, C
.data
extern a:sbyte 
extern b:sbyte
extern c:sbyte
extern numerator:sword
extern denominator:sbyte
extern result:sword
;(2*a/b-1)/(a-28+c)
.code
  ASM_count PROC
;///////////////////////////////numerator///////////////////////////////
xor eax, eax
mov al, 2
imul a
;cbw
idiv b
dec ax
mov numerator, ax

;///////////////////////////////denominator///////////////////////////////
xor eax, eax
mov al, a
sub al, 28
add al, c
mov denominator, al
;///////////////////////////////result///////////////////////////////
xor eax, eax
mov ax, numerator
idiv denominator
mov result, ax
ret
  ASM_count endp
end


This is how the problem manifests itself:
the numbers are calculated correctly, but they are displayed incorrectly.
5f3ac0e8c5963977949043.png
5f3ac0f6f1435862370019.png
5f3ac1025091b927732188.png
Moreover, any value out of three can be displayed incorrectly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-08-17
@Alrond2198

signed __int8 numerator = 0;
signed __int16 denominator = 0;

extern numerator:sword
extern denominator:sbyte
...
mov denominator, al

Do you see that the types in C and in assembler do not match?
In a good way, you need to replace __int8 numeratorwith __int16 numerator, extern denominator:sbytewith extern denominator:swordand mov denominator, alwith mov denominator, ax, so that it becomes as it should.
Everything else looks good.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question