I need to get the difference of 2 signed integers. Is there an ABS() function in x86 assembly language so I can do this. Any help would be greatly appreciated.
If it is x86 assembly, the following according to the ever useful wikipedia should work. Subtract one value from the other and then use these instructions on the result:
cdq
xor eax, edx
sub eax, edx
If you want to handle all cases correctly, you can't just subtract and then take the absolute value. You will run into trouble because the difference of two signed integers is not necessarily representable as a signed integer. For example, suppose you're using 32 bit 2s complement integers, and you want to find the difference between INT_MAX
(0x7fffffff
) and INT_MIN
(0x80000000
). Subtracting gives:
0x7fffffff - 0x80000000 = 0xffffffff
which is -1
; when you take the absolute value, the result you get is 1
, whereas the actual difference between the two numbers is 0xffffffff
interpreted as an unsigned integer (UINT_MAX
).
The difference between two signed integers is always representable as an unsigned integer. To get this value (with 2s complement hardware), you just subtract the smaller input from the larger and interpret the result as an unsigned integer; no need for an absolute value.
Here's one (of many, and not necessarily the best) way do this on x86, assuming that the two integers are in eax
and edx
:
cmp eax, edx // compare the two numbers
jge 1f
xchg eax, edx // if eax < edx, swap them so the bigger number is in eax
1: sub eax, edx // subtract to get the difference
Assuming that your integers are in MMX or XMM registers, use psubd
to compute the difference, then pabsd
to get the absolute value of the difference.
If your integers are in the plain, "normal" registers, then do a subtraction, then the cdq
trick to get the absolute value. This requires using some specific registers (cdq
sign-extends eax
into edx
, using no other register) so you may want to do things with other opcodes. E.g.:
mov r2, r1
sar r2, 31
computes in register r2
the sign-extension of r1
(0 if r1
is positive or zero, 0xFFFFFFFF if r1
is negative). This works for all 32-bit registers r1
and r2
and replaces the cdq
instruction.
A short but straightforward way, using the conditional move instruction (available Pentium and up I think):
; compute ABS(r1-r2) in eax, overwrites r2
mov eax, r1
sub eax, r2
sub r2, r1
cmovg eax, r2
The sub instruction sets the flags the same as the cmp instruction.