Negate a number in assembly

Started by
22 comments, last by Spoonbender 17 years, 12 months ago
Hi, I'd like to know how to negate a number in assembly: a = -a; //a is a 32bit integer I tried mov exa,a; and eax,0xFFFFFFFF; mov a,eax; but this always changes the sign to negative. if a is already a negative number then the result should be positive. I searched the net but can't find anything on that. Please help. Thanks!
Advertisement
multiply it by -1.
xor eax, 0x80000000;

Edit: nm, it's dependant on representation of number.
neg eax
Quote:Original post by Antheus
xor eax, 0x80000000;


this won't work for two's complement representation (used on x86).
Quote:Original post by echohead
Quote:Original post by Antheus
xor eax, 0x80000000;


this won't work for two's complement representation (used on x86).


Yes, it occured to me right after posting.

wow


Thanks guys!
Quote:Original post by JoeZ
and eax,0xFFFFFFFF;

but this always changes the sign to negative.

That's impossible. and eax, 0xffffffff does not change the value at all.
xor would work as well. BTW Have you looked into Intel's manuals?
I am not familiar with x86, but in MIPS you could just do something like:

add $1,$0,-$1

Or you could do a bitwise negation and add 1 for twos-complement numbers.

This topic is closed to new replies.

Advertisement