Introduction

Carry can be a difficult concept to understand. Hopefully this page will help.

Back to school

If you went to school in an English-speaking country, you might be familiar with the word in this context but it is still confusing. If you speak another language you probably have a word for it too.

For example, when adding two numbers:

   27
 + 35
 ----

You can do this easily but consider it at a methodical level. We add seven to five to get twelve; we write a 2 and "carry" the 1 to the next column:

   27
 + 35
 ----
    2
   1

Next we add two, three and the "carried" one to get six and hence the result:

   27
 + 35
 ----
   62
   1

That's great. Now let's do it in binary.

   %01
 + %01
 -----
   %10
    1

There: we "carried" a 1 from bit 0 into bit 1 of the result. For a more realistic case:

   %11111111
 + %00000001
 -----------
  %100000000

The problem here is that the result is bigger than 8 bits; so, we cut off the 1 at the start and store that in the carry bit. This tells us that there was a "carry out" of the high bit of the result and a "carry in" to the Carry flag.

Borrowing

You may remember that at school there was something similar for subtraction; sometimes, you need to "borrow" from the next digit to have enough to make a positive result. Example:

   43
 - 15
 ----

You can't subtract five from three, so you "borrow" one from the next column; thirteen minus five is eight:

    1
   3 3
 - 1 5
 ------
     8

The next digit is then found by subtracting one from three and it is finished.

    1
   3 3
 - 1 5
 -----
   2 8

In binary, much the same happens:

   %110
 - %101
 ------
   %001

As we get up to eight bits, sometimes we need to "borrow" from an imaginary ninth column:

   %00000000         %100000000
 - %10000000       - %010000000
 -----------       ------------
    ????????         %010000000

In these cases, we just "borrow" whatever we need to make it possible to get a result; the carry bit can tell whether anything was "borrowed" from the imaginary ninth bit. You can also describe it as a "carry in" to the high bit from the Carry flag.

What that means in practice

Whenever an addition would make a result bigger then eight bits, the carry flag will become 1; you can use this (with instructions like adc) to add that "carry out" onto another byte so you can effectively chain bytes together to make large numbers.

When a subtraction would make a negative number, the carry flag will become 1 and the result will instead be that negative number plus 256 (in signed notation; in two's complement notation it is a negative number).

When using the carry/no carry conditions with decrements in Z80 code, you need to remember that it becomes 1 on the transition from 0 to -1, which is one step later than the transition from 1 to 0 which triggers the zero condition. This can be useful or equally a tricky bug to discover.




Return to top
0.134s