This short video explains, how computers change the carry flag, when ALU adds or subtracts
two unsigned integers.
The carry flag is a single binary bit, in one of the core registers.
The carry flag is used to indicate, whether ALU has generated a carry out of the most
significant bits.
An example is, what happens if one were to add 28 and 6 using 5-bit registers.
The result should be 34, which is 100010, requiring 6 bits to represent in binary.
The five least significant bits are stored in the result register.
However, the most significant bit is not stored because each register has only five bits.
Therefore, ALU produces 2 as the result, and sets the Carry flag to one, indicating the
result is too large to fit into a 5-bit register.
We can use the number wheel to explain the carry.
Numbers can be added or subtracted by moving round the number wheel, clockwise for addition,
and counterclockwise for subtraction.
In this 5-bit example, carry occurs when a transition is made from 31 to 0.
In other words, if unsigned addition crosses the boundary (31 and 0), the carry flag is set to 1
The borrow flag is set, if A is less than B when computing A minus B.
For example, subtracting 5 from 3, requires a borrow, into the most significant bits subtracted.
In this example, ALU mistakenly produces 30 as the result.
We can also use the number wheel to illustrate this concept.
In this five-bit system, the borrow flag is set to 1 if subtracting two unsigned numbers,
crosses the boundary between 0 and 31 on the number wheel.
ARM Cortex-M microprocessors store the carry flag in one of special-purpose registers.
This register is called program status register (PSR).
This picture shows the content of the program status register.
It is interesting that the Carry and Borrow flags share the same flag bit in the program
status register.
If the C flag bit is 1, it means carry for signed addition, or no borrow for unsigned subtraction.
On the opposite, if C is 0, it means no carry for signed addition, or borrow for unsigned subtraction.
We can use a simple way to member this rule.
ARM Cortex-M microprocessors use the Carry flag bit to represent Borrow for unsigned subtraction.
Carry equals NOT borrow.
Therefore, in the previous example of subtracting 5 from 3, ALU clears the carry flag.
Borrow has been generated.
Therefore, Borrows is 1.
Carry equals NOT borrow.
As result, Carry is zero.
In summary, if the Carry flag in the program status register is 1, then the result of ALU
is incorrect for unsigned addition, but, correct for unsigned subtraction.
If the carry flag is zero, then the ALU result is correct for unsigned addition, but, incorrect
for unsigned subtraction.
Software needs to watch the carry flag to detect any errors.
Please visit the book website for more tutorials and examples.