X86 assembly abs() implementation?

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.

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.

There is the SUB instruction, if what you want is to do A-B. HTH.

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.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions