Alex
Alex

Reputation: 1175

i8086 assembly: CF vs OF and SF

I've looked through numerous topics, but can not figure out if I understood those right.

I will use the notation unsigned/signed.

So, assuming we have a range of single-byte numbers, [0..255]/[0..-1] (2's complement), is it right that:

UPD: how is sign kept at C programming language, for example? Are some additional operations performed to store the sign information separately? In other words, why doesn't it do anything weird as shown below with 0x80+0x80?

Upvotes: 0

Views: 2343

Answers (2)

Ross Ridge
Ross Ridge

Reputation: 39591

The word "carry" in carry flag has the same meaning as when you learned to add multi-digit numbers by "carrying the one" when the result of adding individual digits of the numbers was 10 or higher. In the case of 8-bit addition the carry flag is set when the operation results in "carrying the one" into the non-existent ninth bit of the result. So, yes, you can use the carry flag to interpret the result as a 9-bit value.

The overflow flag is set when the result of the addition isn't representable as a signed value when interpreting the source operands as signed values. So for 8-bit signed addition this means the result is outside the range -128 to 127. (In the case an 8-bit addition the overflow flag is implemented by XOR'ing the carry from the eighth bit to the ninth bit with the carry from the seventh bit to the eighth bit.)

However for signed arithmetic it's not the overflow flag itself that represents the ninth bit of the result. If the overflow flag is set then he carry flag becomes the sign bit of the 9-bit signed value, otherwise it's the sign flag that becomes the ninth bit.

For example when you perform the 8-bit signed calculation -128 + -128 (1000 0000b + 1000 0000b) the result is 0 with the carry and overflow flags set. If you then pretend the carry flag is the ninth bit of a 9-bit signed value then the result of the calculation is -256 (1 0000 0000b).

Upvotes: 1

user35443
user35443

Reputation: 6403

You're right, but the last one thing is not really their purpose.

Let's take the Carry Flag as an example for addition of two 64-bit number on a 32-bit machine.

; adds EDX:ECX to EBX:EAX
add eax, ecx
adc ebx, edx

What happens is that the carry of the first operation is fed to the adder once again for the second doubleword. It's much like keeping the overflow of addition when doing it on a paper: 3 + 9 makes 2, and you remember 1 for the next digit. sbb (subtraction with borrow) is the subtraction alternative to addition with carry.

Overflow Flag tells you that the signed numbers you added have crossed the two´s-complement boundary and that the result can no longer be relied on.

Negative Flag together with OF can be used for comparing two signed numbers.

All of the flags and their purposes have already been described here several times. You can check this out.

Upvotes: 0

Related Questions