PIC subtraction: Carry flag

Status
Not open for further replies.

eblc1388

Active Member
For two 8-bit numbers, 0-255.

Let says 20 & 10.

If you add 20 & 10, you get 30 with no carry.

However, if you subtract 10 from 20, you get 10 and also set the carry flag. Why would the PIC designer choose to do that? I don't know.

This setting of carry flag is easy to get wrong especially when one is used to other processors like 8051.
 
If you add 20 & 10, you get 30 with no carry.

That is obvious of course. You get a carry if you add two numbers and the sum is 256 (100h) or greater.

However, if you subtract 10 from 20, you get 10 and also set the carry flag.

It is easier to understand if you think of subtracting B from A as adding -B to A. In your example, subtracting 10 from 20 is the same as adding -10 to 20. In this case -10 is 0F6h in 8-bit hex. Adding 0F6h+14h equals 10Ah which generates a carry.
 
The carry flag is a borrow bit when it comes to subtraction. It is the 9th bit. You set it before a subtraction, if it gets cleared then a borrow from the high byte has occurred. so, in your example, 20-10 should be thought of as 276 (20+256) - 10 = 266. 266 being 10 + the carry (9th) bit.

So, it's logically the same as when you do addition, I.E. the 9th bit.

HTH

Mike.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…