Question

I'm trying to understand the FLAGS status register.

I know that the carry flag set if an arithmetic operation generates a carry or a borrow out of the most-significant bit of the result, but I also know that it only works when the two numbers added are positive.

Why doesn't it work on the signed operations? I mean why do we have to check the overflow flag instead?

Was it helpful?

Solution

The carry flag is an "unsigned" overflow for addition. if you want to do signed math and are concerned about overflow you need to use the "signed overflow" which is not the same result. binary addition is identical for unsigned and twos complement there is no such thing as signed math in an adder (nor is there such a thing as subtraction), but the flags are taken off of the overflows in different ways. unsigned overflow is simply the carry out of the msbit, signed overflow is a comparison of the carry in and carry out of the msbit, if they match then no signed overflow if they dont match then signed overflow.

Not all hardware implements a signed overflow flag, you are much more likely to find a carry flag (unsigned overflow). A subtraction simply means invert the second operand and invert the carry in of the lsbit (invert and add 1), that is why we have and care about twos complement it makes the hardware so much easier. Different processor families use a different practice for subtract. sometimes the carry out is inverted if the operation was a subtract, sometimes not, so the inversion or not of the carry in on the lsbit for add with carry vs subtract with borrow (if your instruction set has one) is directly affected by this. it is not too hard to figure out what your processor does, some processors dont quite document if a carry set or a carry clear indicates the prior subtract had a borrow or not (unsigned overflow)

Not all hardware has an overflow bit (or a carry out) for that matter, so sometimes you have to synthesize these by examining the msbits of the operands and the result. Or by using other methods. but it all boils down to twos complement vs unsigned, and for addition (and subtraction) they are computed differently.

For multiplication and division this is not the case a signed multiplier and unsigned multiplier are different, use the wrong one you can get the wrong answer, likewise if those have overflow flags then you need to compare them to the operation. the processors databook should tell you this otherwise you have to do some simple experiments to figure it out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top