The MASM Forum

General => The Campus => Topic started by: liquidvel on June 19, 2019, 05:41:04 AM

Title: NEG and the Carry Flag
Post by: liquidvel on June 19, 2019, 05:41:04 AM
Hello MASM Community,
I have a question on the NEG instruction in Intel x86 Assembler.
It basically does returns the two's complement of a number. It subtracts the number from 0.

So let's say I have a number x.
If x is 5, then neg 5 is -5 and the CF is set. This is equivalent for all numbers > 0.

My question: Why is the CF flag set with numbers x < 0? Is it allowed to do the two's complement of a negative number? The two's complement of a negative number does not return its positive counterpart or does it?
Why does neg -5 set the CF flag? Can somebody explain this to me in detail?
Title: Re: NEG and the Carry Flag
Post by: aw27 on June 19, 2019, 06:45:17 AM
Because Intel decided that it is the way to go.   :thumbsup:

Intel® 64 and IA-32 Architectures
Software Developer's Manual


NEG—Two's Complement Negation

.......

Flags Affected
The CF flag set to 0 if the source operand is 0; otherwise it is set to 1. The OF, SF, ZF, AF, and PF flags are set
according to the result.
Title: Re: NEG and the Carry Flag
Post by: Tedd on June 19, 2019, 10:03:46 AM
The real reason is that, as far as the CPU is concerned, negative numbers don't really exist.

The negation of 5 is FFFFFFFBh, which is either 4294967291 or -5 by convention -- the CPU doesn't know or care how you're going to treat it.

So when you do "neg -5" what you're really doing is "neg 4294967291" so the carry/borrow flag is set because a non-zero value was subtracted from zero.
Title: Re: NEG and the Carry Flag
Post by: hutch-- on June 19, 2019, 10:52:09 AM
 :skrewy:

> Can somebody explain this to me in detail?
Tutors cost money where members will help if they have the time, the Intel manuals are your friend and the download is free.